Skip to content

Instantly share code, notes, and snippets.

@troygoode
Created April 6, 2012 18:44
Show Gist options
  • Save troygoode/2322007 to your computer and use it in GitHub Desktop.
Save troygoode/2322007 to your computer and use it in GitHub Desktop.
Prototypal Inheritance
object = (o)->
F = ->
F.prototype = o
new F()
# object to inherit from
parent = name: "Papa"
# the new object
child = object parent
# testing
console.log child.name # "Papa"
# parent constructor
Person = ->
# an "own" property
@name = "Adam"
# a property added to the prototype
Person::getName = ->
@name
# create a new person
papa = new Person()
# inherit
kid = object papa
# test that both the own property
# and the prototype property were inherited
console.log kid.getName() # "Adam"
# parent constructor
Person = ->
# an "own" property
@name = "Adam"
# a property added to the prototype
Person::getName = ->
@name
# inherit
kid = object Person.prototype
console.log(typeof kid.getName) # "function", because it was in the prototype
console.log(typeof kid.name) # "undefined", because only the prototype was inherited
# Addition to ECMAScript 5
child = Object.create parent
child = Object.create parent, age: value: 2
console.log(child.hasOwnProperty("age")) # true
function object(o) {
function F() {
}
F.prototype = o;
return new F();
}
// object to inherit from
var parent = {
name:"Papa"
};
// the new object
var child = object(parent);
// testing
console.log(child.name); // "Papa"
// parent constructor
function Person() {
// an "own" property
this.name = "Adam";
}
// a property added to the prototype
Person.prototype.getName = function () {
return this.name;
};
// create a new person
var papa = new Person();
// inherit
var kid = object(papa);
// test that both the own property
// and the prototype property were inherited
console.log(kid.getName()); // "Adam"
// parent constructor
function Person() {
// an "own" property
this.name = "Adam";
}
// a property added to the prototype
Person.prototype.getName = function () {
return this.name;
};
// inherit
var kid = object(Person.prototype);
console.log(typeof kid.getName); // "function", because it was in the prototype
console.log(typeof kid.name); // "undefined", because only the prototype was inherited
/* Addition to ECMAScript 5 */
var child = Object.create(parent);
var child = Object.create(parent, {
age:{ value:2 } // ECMA5 descriptor
});
console.log(child.hasOwnProperty("age")); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment