Tsayin JavaScript Keywords this

实例

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

亲自试一试

What is this?

JavaScript this The keyword refers to the object it belongs to.

it has different values depending on its usage location:

  • In a method,this Means the owner object.
  • In the case of alone,this Means the global object.
  • In a function,this Means the global object.
  • In a function, in strict mode,this is undefined.
  • In the event,this Means the element that receives the event.

Like call()apply() Such methods can refer to this to any object.

this in method

In object methods,this Means the 'owner' of this method.

In the example at the top of this page,this Means the person object.

The person object is the owner of the fullName method.

fullName : function() {
  return this.firstName + " " + this.lastName;
}

亲自试一试

Single this

In using alone, the owner is the global object, therefore this Means the global object.

In the browser window, the global object is [object Window]

实例

var x = this;

亲自试一试

In strict mode, if used alone, then this Means the global object [object Window]

实例

"use strict";
var x = this;

亲自试一试

this in function (default)

In JavaScript functions, the default binding of the function's owner this

Therefore, in a function,this Means the global object [object Window]

实例

function myFunction() {
  return this;
}

亲自试一试

this in function (strict mode)

JavaScript strict mode does not allow default binding.

Therefore, when used in a function, in strict mode,this is undefined (undefined)。

实例

"use strict";
function myFunction() {
  return this;
}

亲自试一试

this in event handler

In HTML event handlers,this Means the HTML element that receives this event:

实例

<button onclick="this.style.display='none'">
  Click to delete me!
</button>

亲自试一试

Object method binding

In this example,this ya na' person object (person object na' bane' function na' 'owner'):

实例

var person = {
  firstName  : "Bill",
  lastName   : "Gates",
  id         : 678,
  myFunction : function() {
    return this;
  }
};

亲自试一试

实例

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

亲自试一试

换句话说,this.firstName 意味着 this(person)对象的 firstName 属性。

显式函数绑定

call()apply() 方法是预定义的 JavaScript 方法。

它们都可以用于将另一个对象作为参数调用对象方法。

您可以在本教程后面阅读有关 call()apply() 的更多内容。

在下面的例子中,当使用 person2 作为参数调用 person1.fullName 时,this 将引用 person2,即使它是 person1 的方法:

实例

var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"Bill",
  lastName: "Gates",
}
person1.fullName.call(person2);  // 会返回 "Bill Gates"

亲自试一试