Created
July 3, 2012 00:19
-
-
Save tim-smart/3036591 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Parent () { | |
this.name = 'Roger' | |
} | |
Parent.prototype.yell = function yell () { | |
var parent = this | |
console.log('My name is ' + parent.name + '!!') | |
return parent | |
} | |
function Child (name) { | |
var child = this | |
Parent.call(child) | |
// Parent.apply(this, arugments) | |
// ^ That would pass along arguments as well | |
// After calling the parent construction function, | |
// this.name is now set to 'Roger' | |
child.parent = child.name | |
child.name = name | |
} | |
// prototype is the meta object that is assigned to __proto__ on new. | |
// __proto__ is the meta object of an object used for secondary lookup. | |
// Good practice to make sure the constructor is set properly. | |
Child.prototype.__proto__ = Parent.prototype | |
Child.prototype.constructor = Child | |
// Set a member method | |
Child.prototype.talk = function talk () { | |
// It is good practice to assign this to a variable. | |
// It allows you to avoid lots of context problems later on. | |
var child = this | |
console.log('My name is ' + child.name + '. My parent is ' + child.parent) | |
return child | |
} | |
// ==== | |
// Test it. | |
var child = new Child('Charlie') | |
child.yell() | |
child.talk() | |
console.log(child.__proto__ === Child.prototype) | |
console.log(child.__proto__.__proto__ === Parent.prototype) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
My name is Charlie!! | |
My name is Charlie. My parent is Roger | |
true | |
true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment