关于javascript:谈一谈你对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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理