Skip to content

Instantly share code, notes, and snippets.

@getify
Last active September 7, 2016 16:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/5289182 to your computer and use it in GitHub Desktop.
Save getify/5289182 to your computer and use it in GitHub Desktop.
comparing Object.create() object linkage to `new` constructor linkage
// making objects linked via Object.create()
var Foo = Object.create(null);
Foo.me = "Foo";
Foo.identify = function() {
console.log("Me: " + this.me);
};
var Bar = Object.create(Foo);
Bar.me = "Bar";
var bar1 = Object.create(Bar);
bar1.me = "bar1";
var bar2 = Object.create(Bar);
bar2.me = "bar2";
Foo.identify(); // "Me: Foo"
Bar.identify(); // "Me: Bar"
bar1.identify(); // "Me: bar1"
bar2.identify(); // "Me: bar2"
Object.getPrototypeOf(Bar) === Foo;
Object.getPrototypeOf(bar1) === Bar;
Object.getPrototypeOf(bar2) === Bar;
// making objects via constructors called with `new`
function Foo(who) {
this.me = who;
}
Foo.prototype.identify = function() {
console.log("Me: " + this.me);
};
function Bar(who) {
Foo.call(this,who); // a mixin but hard-coded to its parent
}
Bar.prototype = new Foo();
var bar1 = new Bar("bar1");
var bar2 = new Bar("bar2");
bar1.identify(); // "Me: bar1"
bar2.identify(); // "Me: bar2"
bar1 instanceof Bar; // true
bar2 instanceof Bar; // true
bar1 instanceof Foo; // true
bar2 instanceof Foo; // true
// making objects via constructors called with `new`
// mimicking a bit of what YUI does I guess?
function Foo(who) {
this.me = who;
}
Foo.prototype.identify = function() {
console.log("Me: " + this.me);
};
function Bar(who) {
Foo.call(this,who); // a mixin but hard-coded to its parent
}
Bar.superclass = Foo.prototype;
Bar.prototype = Object.create(Foo.prototype);
var bar1 = new Bar("bar1");
var bar2 = new Bar("bar2");
bar1.identify(); // "Me: bar1"
bar2.identify(); // "Me: bar2"
bar1 instanceof Bar; // true
bar2 instanceof Bar; // true
bar1 instanceof Foo; // true
bar2 instanceof Foo; // true
// making objects linked via Object.create()
// this is the same as file 1 above, but uses a `init()`
// note: no hard-coding of the "inheritance" structure here
var Foo = Object.create(null);
Foo.init = function(who) {
this.me = who;
};
Foo.identify = function() {
console.log("Me: " + this.me);
};
var Bar = Object.create(Foo);
Bar.init("Bar");
var bar1 = Object.create(Bar);
bar1.init("bar1");
var bar2 = Object.create(Bar);
bar2.init("bar2");
bar1.identify(); // "Me: bar1"
bar2.identify(); // "Me: bar2"
Object.getPrototypeOf(Bar) === Foo;
Object.getPrototypeOf(bar1) === Bar;
Object.getPrototypeOf(bar2) === Bar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment