简体   繁体   English

使用关键字“this”有什么好处?

[英]What are the benefits of using the keyword “this”?

The following code: 以下代码:

var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return cody.gender;} 
};

is the same as : 是相同的 :

var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return this.gender;} 
};

Both codes acheive the same target. 两个代码都实现了相同的目标。 The only difference is the swap of cody with the keyword this . 唯一的区别是cody与关键字this的交换。 What is the benefits of using the keyword this in Javascript? 在Javascript中使用关键字this有什么好处? Does it boost the performance? 它会提升性能吗? can we ignore it in OOP? 我们可以在OOP中忽略它吗?

this refers to the current instantiation of the structure in question. this指的是当前有关结构的实例化。 For example, the following will fail: 例如,以下内容将失败:

var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return cody.gender}
};
var codyCopy = cody;
cody = "foobar";
//undefined
alert(codyCopy.getGender());

However, using this will not, because it correctly refers to the codyCopy : 但是,使用this不会,因为它正确引用了codyCopy

var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return this.gender}
};
var codyCopy = cody;
cody = "foobar";
//male
alert(codyCopy.getGender());

The 'this' keyword is used to refer to the current execution context or object your code is in. It is useful when you want to define a type of object aka a class for example people: 'this'关键字用于指代当前执行上下文或代码所在的对象。当您想要定义一种类型的对象(例如人类)时,它非常有用:

var Person = function(name, living, age, gender) {
    this.name = name;
    this.living = living;
    this.age = age;
    this.gender = gender;
    this.getGender = function(){return this.gender};
};

var cody = new Person('Cody', true, 23, 'male');
var john = new Person('John', true, 25, 'male');

This allows you to use the 'new' keyword to create multiple unique instances of Person with their own values. 这允许您使用'new'关键字创建具有各自值的Person的多个唯一实例。 So on the line var cody = new Person('Cody', true, 23, 'male'); 所以就行var cody = new Person('Cody', true, 23, 'male'); 'this' refers to the cody var and on the next line it refers to the john var. 'this'指的是cody var,在下一行指的是john var。 In your code 'this' refers to your cody var because it is inside the cody object but it is not necessary because you aren't creating new codys with there own values. 在你的代码中'this'指的是你的cody var,因为它在cody对象里面但是没有必要因为你没有用自己的值创建新的codys。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM