Skip to content

Instantly share code, notes, and snippets.

@tim-smart
Created July 3, 2012 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tim-smart/3036591 to your computer and use it in GitHub Desktop.
Save tim-smart/3036591 to your computer and use it in GitHub Desktop.
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)
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