Created
March 2, 2013 14:32
-
-
Save Sljubura/5071249 to your computer and use it in GitHub Desktop.
Prototypal inheritance /w and /wo ECMAScript 5
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 object(o) { // Simple prototypal inheritance | |
function Proxy() {} | |
Proxy.prototype = o; | |
return new Proxy(); | |
} | |
function Person() { | |
this.name = "Vladimir" | |
} | |
Person.prototype.getName = function () { | |
return this.name; | |
}; | |
// Create a new person | |
var parent = new Person(); | |
var child = object(parent); // Inherit from parent | |
child.getName(); // "Vladimir" | |
// In this example, child inherit both the prototype functionality and properties | |
// ------------------------------------------------------------------------------ | |
function Person() { | |
this.name = "Sljubura" | |
} | |
Person.prototype.getName = function () { | |
return this.name; | |
}; | |
var child = object(Person.prototype); // There is no need to instantiate Person() object | |
typeof child.getName; // "function" - inherits from prototype | |
typeof child.name; // "undefined" - only prototype is inherited | |
// ------------------------------------------------------------------------------ | |
// ECMAScript 5 | |
var child = Object.create(parent); // or | |
var child = Object.create(parent, { | |
age: { value: 2 } | |
}); | |
child.hasOwnProperty("age"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment