Skip to content

Instantly share code, notes, and snippets.

@Sljubura
Created March 2, 2013 14:32
Show Gist options
  • Save Sljubura/5071249 to your computer and use it in GitHub Desktop.
Save Sljubura/5071249 to your computer and use it in GitHub Desktop.
Prototypal inheritance /w and /wo ECMAScript 5
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