Created
August 7, 2013 02:48
-
-
Save seekerlee/6170769 to your computer and use it in GitHub Desktop.
JS OOP
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
var ninja = (function(){ | |
function Ninja(){} | |
return new Ninja(); | |
})(); | |
// Make another instance of Ninja | |
var ninjaB = new ninja.constructor(); | |
assert( ninja.constructor == ninjaB.constructor, "The ninjas come from the same source." ); |
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
function Person(){} | |
Person.prototype.dance = function(){}; | |
function Ninja(){} | |
// Achieve similar, but non-inheritable, results | |
Ninja.prototype = Person.prototype; | |
Ninja.prototype = { dance: Person.prototype.dance }; | |
assert( (new Ninja()) instanceof Person, "Will fail with bad prototype chain." ); | |
// Only this maintains the prototype chain | |
Ninja.prototype = new Person(); | |
var ninja = new Ninja(); | |
assert( ninja instanceof Ninja, "ninja receives functionality from the Ninja prototype" ); | |
assert( ninja instanceof Person, "... and the Person prototype" ); | |
assert( ninja instanceof Object, "... and the Object prototype" ); |
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
function User(first, last){ | |
if ( !(this instanceof User) ) //if ( !(this instanceof arguments.callee) ) | |
return new User(first, last); | |
this.name = first + " " + last; | |
} | |
var name = "Resig"; | |
var user = User("John", name); | |
assert( user, "This was defined correctly, even if it was by mistake." ); | |
assert( name == "Resig", "The right name was maintained." ); |
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
// Private properties, using closures. | |
function Ninja(){ | |
var slices = 0; | |
this.getSlices = function(){ | |
return slices; | |
}; | |
this.slice = function(){ | |
slices++; | |
}; | |
} | |
var ninja = new Ninja(); | |
ninja.slice(); | |
assert( ninja.getSlices() == 1, "We're able to access the internal slice data." ); | |
assert( ninja.slices === undefined, "And the private data is inaccessible to us." ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment