Adding a prototyped method to a function.
function Ninja(){}
Ninja.prototype.swingSword = function(){
return true;
};
var ninjaA = Ninja();
assert( !ninjaA, "Is undefined, not an instance of Ninja." );
var ninjaB = new Ninja();
assert( ninjaB.swingSword(), "Method exists and is callable." );
Properties added in the constructor (or later) override prototyped properties.
function Ninja(){
this.swingSword = function(){
return true;
};
}
// Should return false, but will be overridden
Ninja.prototype.swingSword = function(){
return false;
};
var ninja = new Ninja();
assert( ninja.swingSword(), "Calling the instance method, not the prototype method." );
Prototyped properties affect all objects of the same constructor, simultaneously, even if they already exist.
function Ninja(){
this.swung = true;
}
var ninjaA = new Ninja();
var ninjaB = new Ninja();
Ninja.prototype.swingSword = function(){
return this.swung;
};
assert( ninjaA.swingSword(), "Method exists, even out of order." );
assert( ninjaB.swingSword(), "and on all instantiated objects." );
QUIZ: Make a chainable Ninja method.
function Ninja(){
this.swung = true;
}
var ninjaA = new Ninja();
var ninjaB = new Ninja();
// Add a method to the Ninja prototype which
// returns itself and modifies swung
assert( !ninjaA.swing().swung, "Verify that the swing method exists and returns an instance." );
assert( !ninjaB.swing().swung, "and that it works on all Ninja instances." );
The chainable method must return this.
function Ninja(){
this.swung = true;
}
var ninjaA = new Ninja();
var ninjaB = new Ninja();
Ninja.prototype.swing = function(){
this.swung = false;
return this;
};
assert( !ninjaA.swing().swung, "Verify that the swing method exists and returns an instance." );
assert( !ninjaB.swing().swung, "and that it works on all Ninja instances." );
[