Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
45 lines (37 sloc) 1.11 KB
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Classical Pattern #3 - Rent and Set Prototype (a pattern that should be generally avoided)
Description: first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
*/
// the parent constructor
function Parent(name) {
this.name = name || 'Adam';
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};
// child constructor
function Child(name) {
Parent.apply(this, arguments);
}
Child.prototype = new Parent();
var kid = new Child("Patrick");
console.log(kid.name); // "Patrick"
console.log(typeof kid.say); // function
console.log(kid.say()); // Patrick
console.dir(kid);
delete kid.name;
console.log(kid.say()); // "Adam"
// Drawback - the parent constructor is called twice, so it could be inefficient
// reference
// http://shop.oreilly.com/product/9780596806767.do
</script>
</body>
</html>