全面理解JavaScript中的 this

全面理解JavaScript中的 this

上下文 VS 作用域

作用域(scope) 是在运行时代码中的某些特定部分中变量,函数和对象的可访问性。换句话
说,作用域决定了代码区块中变量和其他资源的可见性。而上下文
(context)是用来指定代码某些特定部分中 this 的值。

作用域是基于函数(function-based)的,而上下文是基于对象
(object-based)的。换句话说,作用域是和每次函数调用时变量的访问有关,并且每次调 > 都是独立的。上下文总是被调用函数中关键字 this 的值,是调用当前可执行代码的对象的 > 引用。说的通俗一点就是: this 取值,是在函数真正被调用执行的时候确定的,而不是在
函>数定义的时候确定的。

全局对象

  • window
  • global

函数上下文

  • 全局对象
  • 当前对象
  • 任意对象

作为函数直接调用

  • 非严格模式
function fun() {
    return this;
}

this === window  // browser
this === global // node.js
  • 严格模式 “use strict”

在严格模式下, this 将保持他进入执行上下文时的值,所以下面的 this 并不会指向全局对象,而是默认为 undefined 。

'use strict';
function fun() {
    return this;
}

this === undefined //true

作为对象的方法调用

var obj = {
    name: "nicholas",
    getName:function () {
        return this.name;
    }
};
obj.getName() // "nicholas"

// 等价于

var obj = {
    name:"nicholas"
};
function getName() {
    return this.name;
}
obj.getname = getName;

作为构造函数调用

function Person(name) {
    this.name = name;
}
var p = new Person('nicholas');
console.log(p.name); // "nicholas" 

箭头函数中的this

在箭头函数中,this 与 封闭的词法上下文的 this 保持一致,也就是说由上下文确定。

var obj = {
    x: 10,
    foo: function() {
        var fn = () => {
            return () => {
                return () => {
                    console.log(this);      //{x: 10, foo: ƒ} 即 obj
                    console.log(this.x);    //10
                }
            }
        }
        fn()()();
    }
}
obj.foo();

Reference

全面理解JavaScript中的 this

猜你喜欢

转载自www.cnblogs.com/rosendolu/p/10066537.html