谈一谈你对this的了解?Can you talk about your understanding of this ?

微信扫一扫,分享到朋友圈

谈一谈你对this的了解?Can you talk about your understanding of this ?

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

微信扫一扫,分享到朋友圈

谈一谈你对this的了解?Can you talk about your understanding of this ?

和自动驾驶大佬聊聊:谷歌、特斯拉、滴滴自动驾驶哪家强?【下集DannyPal 03】

上一篇

游戏MCN这门生意

下一篇

你也可能喜欢

谈一谈你对this的了解?Can you talk about your understanding of this ?

长按储存图像,分享给朋友