javascript this 关键字 for study

Unlike variables, the this keyword does not have a scope, and nested functions do not
inherit the this value of their caller. If a nested function is invoked as a method, its
this value is the object it was invoked on. If a nested function is invoked as a function
then its this value will be either the global object (non-strict mode) or undefined (strict
mode). It is a common mistake to assume that a nested function invoked as a function
can use this to obtain the invocation context of the outer function. If you want to access
the this value of the outer function, you need to store that value into a variable that is
in scope for the inner function. It is common to use the variable self for this purpose.
For example:
var o = {                           // An object o.
    m: function() {                 // Method m of the object.
        var self = this;            // Save the this value in a variable.
        console.log(this === o);    // Prints "true": this is the object o.
        f();                        // Now call the helper function f().
        function f() {              // A nested function f
           console.log(this === o); // "false": this is global or undefined
           console.log(self === o); // "true": self is the outer this value.
        }
    }
};

o.m();                              // Invoke the method m on the object o.



来自[JavaScript权威指南(第6版)].(JavaScript:The.Definitive.Guide).David.Flanagan

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值