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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值