Reputation: 41909
Working through Secrets of the JavaScript Ninja, I'm looking at constructors with respect to the this
keyword.
function Ninja() {
this.skulk = function() { return this; }
}
Example:
var ninja1 = new Ninja();
window.onload = function() {
assert(ninja1.skulk() === ninja1,
"the 1st ninja is skulking");
};
Output: the 1st ninja is skulking
However, if I add var windowNinja = Ninja()
, why am I seeing this JavaScript error in Chrome?
assert(windowNinja.skulk() === window,
"the window ninja is skulking");
output: JavaScript error: Uncaught TypeError: Cannot call method 'skulk' of undefined
Upvotes: 1
Views: 107
Reputation: 97672
Ninja
doesn't return anything so if you dont initiate an instance of it with new it returns undefined and that is stored in windowNinja
. You can just call
Ninja();
assert(window.skulk() === window,
"the window ninja is skulking");
So the this
in Ninja
is the global object(window) so you're assigning a method skulk
to it. which returns the object that invoked it.
Alternately you can add a return to the function
function Ninja() {
this.skulk = function() { return this; }
return this;
}
Upvotes: 2