JavaScript Patterns

Page 138

Another thing about using a generic inherit() function is that it doesn’t enable you to pass parameters to the child constructor, which the child then passes to the parent. Consider this example: 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.

Classical Pattern #2—Rent-a-Constructor This next pattern solves the problem of passing arguments from the child to the parent. It borrows the parent constructor, passing the child object to be bound to this and also forwarding any arguments: 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. Using the borrowed constructor pattern, the children objects get copies of the inherited members, unlike the classical #1 pattern where they only get references. The following example illustrates the difference: // 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

120 | Chapter 6: Code Reuse Patterns


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.