关于javascript:谈一谈你对this的了解Can-you-talk-about-your-understanding-of-this

5次阅读

共计 1964 个字符,预计需要花费 5 分钟才能阅读完成。

谈一谈你对 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

正文完
 0