日期:2014-05-16 浏览次数:20391 次
5.Inheritance Pattern
function inherit(C, P) { C.prototype = new P(); }???? It’s important to remember that the prototype property should point to an object, not a function, so it has to point to an instance (an object) created with the parent constructor, not to the constructor itself. In other words, pay attention to the new operator, because you need it for this pattern to work.Later in your application when you use new Child() to create an object, it gets functionality from the Parent() instance via the prototype, as shown in the following example:
var kid = new Child(); kid.say(); // "Adam"?Drawbacks When Using Pattern #1
var s = new Child('Seth'); s.say(); // "Adam"?? This is not what you’d expect. It’s possible for the child to pass parameters to the parent’s constructor, but then you have to do the inheritance every time you need a new child, which is inefficient, because you end up re-creating parent objects over and over.
function Child(a, c, b, d) { Parent.apply(this, arguments); }??? This way you can only inherit properties added to this inside the parent constructor.You don’t inherit members that were added to the prototype.
// a parent constructor function Article() { this.tags = ['js', 'css']; } var article = new Article(); // a blog post inherits from an article object // via the classical pattern #1 function BlogPost() {} BlogPost.prototype = article; var blog = new BlogPost(); // note that above you didn't need `new Article()` // because you already had an instance available // a static page inherits from article // via the rented constructor pattern function StaticPage() { Article.call(this); } var page = new StaticPage(); alert(article.hasOwnProperty('tags')); // true alert(blog.hasOwnProperty('tags')); // false alert(page.hasOwnProperty('tags')); // true?
function Cat() { this.legs = 4; this.say = function () { return "meaowww"; } } function Bird() { this.wings = 2; this.fly = true; } function CatWings() { Cat.apply(this); Bird.app