Created
December 2, 2012 04:01
-
-
Save mkuklis/4186901 to your computer and use it in GitHub Desktop.
inheritance and Object.create
This file contains hidden or 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
// resources gathered around inheritance and Object.create | |
// http://ericleads.com/2012/09/stop-using-constructor-functions-in-javascript/ | |
// https://speakerdeck.com/anguscroll/parlez-vous-javascript | |
// http://dailyjs.com/2012/06/04/js101-object-create/ | |
// inheritance via prototype | |
// both constructors A, B are initialized | |
function A() { | |
console.log("init A"); | |
this.log = "A"; | |
} | |
function B() { | |
console.log('init B'); | |
this.log = "B"; | |
} | |
B.prototype.print = function () { | |
console.log(this.log); | |
} | |
A.prototype = new B(); | |
var a1 = new A(); | |
a1.print(); | |
// inheritance via Object.create | |
// D constructor not initialized | |
function C() { | |
console.log('init C'); | |
this.log = 'C'; | |
} | |
// D never executed | |
function D() { | |
console.log('init D'); | |
this.log = "D"; | |
} | |
D.prototype.print = function () { | |
console.log(this.log); | |
} | |
C.prototype = Object.create(D.prototype); | |
var c = new C(); | |
c.print(); | |
// no constructors | |
var mixin = { | |
print: function () { | |
console.log(this.log); | |
} | |
}; | |
var createE = function createE() { | |
return Object.create(mixin, {log: {value: "E"}}); | |
}; | |
var e = createE(); | |
e.print(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment