箭头表达式中的this

箭头表达式中的 this 被设置为他被创建时的上下文

        var globalObj = this;
        console.log(globalObj);  //在全局上下文中this 为 window

        (function() {
            console.log(this);   //调用该函数的this也为window
            console.log(this === globalObj);
        })();


        var obj = {
            func: function() {
                console.log("=========seperator func==========");
                var funcThis = (function() {  
                    console.log(this);
                    return this;
                })();   
                console.log(this);   //this指向func的调用者,或者在通过call、apply、bind等方式动态指定
                console.log(funcThis);  //funcThis指向window,匿名函数虽然在func中定义,但其调用者为window
                console.log(funcThis === this);  //false
            },

            func2: function() {
                console.log("=========seperator func2==========");
                var funcThis = (() => this)();  
                console.log(this);    //this指向func2的调用者,或者在通过call、apply、bind等方式动态指定
                console.log(funcThis);  //this指向func2的this,即定义箭头表达式的上下文,与其本身的调用者无关
                console.log(funcThis === this);  //true
            }
        }

        obj.func();
        obj.func2();

此外,

使用 call 和 apply 函数的时候要注意,如果传递给 this 的值不是一个对象,JavaScript 会尝试使用内部 ToObject 操作将其转换为对象。因此,如果传递的值是一个原始值比如 7 或 'foo',那么就会使用相关构造函数将它转换为对象,所以原始值 7 会被转换为对象,像 new Number(7) 这样,而字符串 'foo' 转化成 new String('foo') 这样,例如:

function bar() {
  console.log(Object.prototype.toString.call(this));
}

//原始值 7 被隐式转换为对象
bar.call(7); // [object Number]

 参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this

猜你喜欢

转载自blog.csdn.net/qq_33265520/article/details/83788776
今日推荐