Created
May 26, 2012 18:48
-
-
Save banksJeremy/2794914 to your computer and use it in GitHub Desktop.
Basic Prototypes
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
// JavaScript could have had nice, clean, minimal prototypal inheritance, but | |
// for political reasons this was obscured behind confusing class-like syntax. | |
// A cleaner prototype implementation would just use two straightforward operators or methods: | |
// - `extend` creates an new object that inherits from another, optionally specifying | |
// properties to be set on the new object. | |
// - `isa` checks if one object is or inherits from another. | |
var original = ExtendableObject.extend({ | |
name: "John", | |
age: 22 | |
}); | |
var childA = original.extend({ | |
name: "Bob" | |
}); | |
var childB = original.extend({ | |
name: "Sarah" | |
}); | |
childA.age === 22; | |
parent.age = 40; | |
childA.age === 42; | |
childA.isa( childA ) === true; | |
childA.isa( childB ) === false; | |
childA.isa( original ) === true; | |
childA.isa( ExtendableObject ) === true; | |
// Do you now how to implement `extend` and `isa` in JavaScript? | |
// No? | |
// Your mind has been filled with classish cruft, | |
// obscuring the true workings of JavaScript's object model! | |
var ExtendableObject = { | |
extend: function( properties ) { | |
var constructor = function(){}; | |
constructor.prototype = this; | |
var instance = new constructor; | |
for (key in properties) { | |
instance[key] = properties[key]; | |
} | |
return instance; | |
}, | |
isa: function( prototype ) { | |
var constructor = function(){}; | |
constructor.prototype = prototype; | |
return this === prototype || this instanceof constructor; | |
} | |
}; | |
childA.isa( Object ) === false; // because you don't inherit from the Object constructor... | |
childA.isa( Object.prototype ) === true; // ...you inherit from its prototype! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment