JavaScript 核心概念 this

this 关键字

In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
this 指的是拥有当前代码的对象。

注意:this 是一个关键字,不是一个变量,因此不能修改 this 的值。

  • 在函数内部使用 this,指的是拥有该函数的对象
  • 在对象内部使用 this,指的是该对象本身
function f() {
  // 在函数内部使用 this,指的是拥有该函数的对象,即当前 window 对象
  console.log(this === window); // true。
}

f();

// 在对象内部使用 this,指的是该对象本身,即当前 window 对象
console.log(this === window); // true

this binding 绑定

this binding is determined by where the function get called:

  • called directly 默认绑定
  • called by object 隐式绑定
  • called by call() and apply() function 显式绑定
  • called by new keyword

通过直接使用 this 进行默认绑定

bind to global object 默认绑定到全局变量

var foo = 1;

function f() {
  console.log(this.foo);
}

f(); // 1

通过对象进行隐式绑定

var obj = {
    num: 1,
    say: function() {
        console.log(this.num);
    }
};

obj.say(); // 1

通过call() 和 apply() 函数进行显式绑定

var obj = {
    num: 1,
    say: function() {
        console.log(this.num);
    }
};

var baz = {
   say: obj.say
};
baz.say(); // undefined,因为此时的 this 指的是 baz,而 baz 不含变量 num

baz.say.call(obj); // 1,通过 call() 显式将 this 绑定到 obj
baz.say.apply(obj); // 1,通过 apply() 显式将 this 绑定到 obj

通过new进行显式绑定

function Foo() {
    this.bar = 1;    
}

var foo1 = new Foo();
console.log(foo1.bar); // 1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容