1

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

asked Dec 26, 2013 at 19:52

2 Answers 2

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;
}
answered Dec 26, 2013 at 20:00
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked. To learn, I put a console.log(windowNinja) after var windowNinka = Ninja() and saw undefined.
0

You left out new, var windowNinja = new Ninja();

answered Dec 26, 2013 at 19:54

4 Comments

The assert fails when I add new.
Hmm, windowNinja.skulk() === windowNinja? I guess without the new skulk would have been added to window so window.skulk() === window would have worked.
yeah. Musa's answer demonstrates that. I tried 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?
Yes it is a scope thing. It looks like Chrome applied Ninja to some object then totally forgot about the window you had just made and accessed the global one for the assert.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.