this 在函数执行时指向 学习笔记

Functions as object's Methods Invoked have one very important property: the object through which a method invoked become the value of the this keyword within the body of the method.


The Scope of this when function invoked
When a function is invoked as a function rather than as a method , the this keyword refers to the global object. Confusingly this is true even when a nested function is invoked( as function) within a containing method that was invoked as a method: the this keyword has one value in the containing function but(counterintuitively) refers to the global object within the body of the nested function.


javascript syntax does not allow you to assign a value to this.


Javascript The Definitive Guide 5th Edition 8.4 Functions as Methods

以上内容摘自javascript权威指南,当一个函数执行时是以对象的方法调用的,那么this指向调用方法的对象本身。如果函数是以函数的形式调用的,那么函数体内的this永远指向全局对象,浏览器端全局对象就是window了,嵌套函数也是如此。

以下面的代码为例:
var calc = {
	op1 : 1,
	op2 : 2,
	op3 : this.op1 + this.op2,
	calc1 : function () {
		return this.op1 + this.op2;
	},
	calc2 : function () {
		return this.op3;
	}
}
alert(calc.calc1());
alert(calc.calc2());
alert(calc.op3);
 
根据以上说明,想一下上面的的运行结果是什么 ?
以下为结果,请选择后可见
3
NaN
NaN
想到了吗?

author:mooring
date:2012/10/14

你可能感兴趣的:(JavaScript)