Javascript 的函数调用模式,有意思的表现

看《JavaScript:the good parts》一书中讲到Javascript方法调用的四种方式,其中比较难理解的是function invocation pattern ,因为其中讲到了Javascript设计的一个缺陷,原文中这么说:

When a function is not the property of an object, then it is invoked as a function:
var sum = add(3, 4); // sum is 7
When a function is invoked with this pattern, this is bound to the global object.
This was a mistake in the design of the language. Had the language been designed
correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function.
因为这里没有给代码, 我理解了半天也没感觉这是个缺陷,因为我觉得当你调用add(3,4);的时候,理应this指向全局变量呀。于是我找了一些文章,大部分也都没有对此进行解释,看来大家都很聪明,没办法,自己测试一下。

代码如下:

int1 = 4;
obj = {
    int1: 5,
    outer: function () {
        function inner() {
            console.log(this.int1);
        };
        inner();
        console.log(this.int1);
    }
};
obj.outer();


运行结果会是:

4
5
看来确实有作者说的那个问题,即当inner();调用时,this指向的是最外层的对象,甚至都不是obj。

但有意思的是下面的一段代码:

int1 = 4;
obj = {
    int1: 5,
    outer: function () {
        int1 = 6;
        function inner() {
            console.log(this.int1);
        };
        inner();
        console.log(this.int1);
    }
};
obj.outer();
可以看出来这段代码对前面的修改微乎其微,只是简单增加了一句int1 = 6;但这次的运行结果是:

6
5
可见,这次调用inner();时this指向的不再是全局的变量,二十outer的变量,这忽上忽下的this指针把我搞晕了,具体的实现我还没搞懂。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值