THIS Institute on Twitter: "Welcome to our latest cohort of post ...

谈一谈你对 this 的了解?

this 的指向不是在编写时确定的,而是在执行时确定的,同时,this 不同的指向在于遵循了一定的规则。

首先,在默认情况下,this是指向全局对象的,比如在浏览器就是指向window

name = "Bale";

function sayName () {
    console.log(this.name);
};

sayName(); //"Bale"

其次,如果函数被调用的位置存在上下文对象时,那么函数是被隐式绑定的。

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

var obj = {
    name: "Messi",
    f: f
};

obj.f(); //被调用的位置恰好被对象obj拥有,因此结果是Messi

再次,显示改变this指向,常见的方法就是callapplybind

bind为例:

function f() {
    console.log( this.name );
}
var obj = {
    name: "Messi",
};

var obj1 = {
     name: "Bale"
};

f.bind(obj)(); //Messi ,由于bind将obj绑定到f函数上后返回一个新函数,因此需要再在后面加上括号进行执行,这是bind与apply和call的区别

最后,也是优先级最高的绑定 new 绑定。

new 调用一个构造函数,会创建一个新对象, 在创造这个新对象的过程中,新对象会自动绑定到Person对象的this上,那么 this 自然就指向这个新对象。

function Person(name) {
  this.name = name;
  console.log(name);
}

var person1 = new Person('Messi'); //Messi
绑定优先级: new绑定 > 显式绑定 >隐式绑定 >默认绑定

Can you talk about your understanding of this ?

The direction of this is not determined at the time of wraiting, but determined at the time of execution. At the same time, the different direction of this lies in following certain rules.

First of all, by default, the this refers to the object of global, such as which refers to the window in browser.

name = "Bale";

function sayName () {
    console.log(this.name);
};

sayName(); //"Bale"

Second, if there is a context object at the location where the function is called, then the function is implicitly bound.

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

var obj = {
    name: "Messi",
    f: f
};

obj.f(); //被调用的位置恰好被对象obj拥有,因此结果是Messi

Again, this display changes this point, the common methods are callapplybind

Take bind as an example:

function f() {
    console.log( this.name );
}
var obj = {
    name: "Messi",
};

var obj1 = {
     name: "Bale"
};

f.bind(obj)(); //Messi ,由于bind将obj绑定到f函数上后返回一个新函数,因此需要再在后面加上括号进行执行,这是bind与apply和call的区别

Finally, it is the binding new with the highest priority.

Calling a constructor function with new keyword, and it will create a new object. in the process of creating new object, the new object will be bound the this in Person object automatically, and then the this will point to the new object naturally.

function Person(name) {
  this.name = name;
  console.log(name);
}

var person1 = new Person('Messi'); //Messi
Binding priority: new Binding > explicit binding > implicit binding > default binding

Damiao_Lee
10 声望1 粉丝

my name is damiao.