问题
I have code like this:
function demo() {
this.val=5;
function() {
this.val=7;
}();
}
Now when I give execute this code in the firefox or chrome console it gives a syntax error. I don't understand why this is an error because I have read that javascript functions are objects so when I call the anonymous function, inside it this points to function demo and should change the val to 7, so if I do
var x=new demo();
x.val; //should give 7
but when I do this
function demo() {
this.val=5;
var f=function() {
this.val=7;
}();
}
window.val; // gives 7
I don't understand if functions are objects then why the this in the anonymous function points to window and not demo.
Please explain this.
回答1:
i dont understand why this is an error
because
function() {
this.val=7;
}();
is evaluated as function declaration and function declarations need a name. To make it interpreted as function expression, you need to put it in parenthesis:
(function() {
this.val=7;
}());
(making it an immediate function)
or assign the function to a variable:
var f = function() {....};
f();
What you do in the second snippet is a mixture of both and although being valid, it does not make much sense. f will have the value undefined.
i dont understand if functions are objects then why the this in the anonymous function points to
windowand notdemo.
Functions don't inherit the context they are called in. Every function has it's own this and what this refers to is determined by how the function is called. It basically boils down to:
"Standalone" (
func()) or as immediate function ((function(){...}())) :thiswill refer to the global object (windowin browsers)As property of an object (
obj.func()):thiswill refer toobjWith the new [docs] keyword (
new Func()):thisrefers to an empty object that inherits fromFunc.prototypeapply [docs] and call [docs] methods (
func.apply(someObj)):thisrefers tosomeObj
Further reading:
- MDC JavaScript Guide - Functions
- MDC JavaScript Reference - Function and functions scope
- ECMAScript 5, Section 13 - Function Definition
回答2:
You can do what you described like this:
function demo() {
var self=this;
this.val = 5;
var f = (function() {
self.val = 7;
})();
}
来源:https://stackoverflow.com/questions/6796521/what-is-the-context-of-an-anonymous-function