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
2 Answers 2
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;
}
1 Comment
console.log(windowNinja) after var windowNinka = Ninja() and saw undefined.You left out new, var windowNinja = new Ninja();
4 Comments
assert fails when I add new.var window = new Ninja(), but assert(window.skulk() === window, ...) showed a JS error that "global window object does not have a skulk method". Also, I'm guessing using var window is bad practice as window is a global object, right?