In the book JavaScript Enlightenment (the link is to a pre-published version (page 85), but I have the published version (Chapter 6.3) and it says the same thing), it says that any inner function will treat this
as the global object (window
) in ECMA-3, but will be fixed in ECMA-5.
The code is below:
http://jsfiddle.net/javascriptenlightenment/9GJhu/
var myObject = {
func1: function() {
console.log(this); // logs myObject
var func2 = function() {
console.log(this) // logs window, and will do so from this point on
var func3 = function() {
console.log(this); // logs window, as it’s the head object
}();
}();
}
}
myObject.func1();
But I thought the current Chrome, Firefox, and node.js should be implementing ECMA-5 to a large degree, so I tried the above code in them and they still print out the global object inside of func2
and func3
. I then added "use strict";
to func1
and just in case, also to func2
and func3
. The code: http://jsfiddle.net/9GJhu/6/ Now in Chrome and node.js, the this
will get printed out as undefined
, instead of myObject
. So according to the book, this
should be myObject
in ECMA-5. What is wrong in the code above?