0

This Javascript code is using the 'this' keyword inside a nested function (which is nested within a constructor):

o=new MyCtor();
for (var p in o) {
  print(p);
  print(o[p]);
}
function MyCtor() {
  this.a=1;
  var instance=this;
  nested();
  function nested() {
    this.b=2;
    instance.c=3;
  }
}

Result is this:

a
1
c
3

Note the print() just dumps the output to the screen like alert() in a browser (I'm testing with a standalone Spidermonkey, not inside a browser). Notice that property 'b' cannot be created by the 'this.b'.

Just wondering what is 'this' refering to in a nested function inside a constructor?

1

2 Answers 2

1

Since you are calling the function directly (not as an object property) and without the new keyword, this is the default object (window in a web browser, global in node, etc).

See a live demo on jsfiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

It refers to the Window. See for yourself by running this fiddle and opening the console: http://jsfiddle.net/sveinatle/9brLj/

Comments

Your Answer

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.