![](/img/trans.png)
[英]What are the benefits and drawbacks of using the 'this' keyword in a constructor function over the prototype property?
[英]What are the benefits of using the keyword “this”?
以下代碼:
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return cody.gender;}
};
是相同的 :
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return this.gender;}
};
兩個代碼都實現了相同的目標。 唯一的區別是cody與關鍵字this的交換。 在Javascript中使用關鍵字this有什么好處? 它會提升性能嗎? 我們可以在OOP中忽略它嗎?
this
指的是當前有關結構的實例化。 例如,以下內容將失敗:
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return cody.gender}
};
var codyCopy = cody;
cody = "foobar";
//undefined
alert(codyCopy.getGender());
但是,使用this
不會,因為它正確引用了codyCopy
:
var cody = {
living:true,
age:23,
gender:'male',
getGender:function(){return this.gender}
};
var codyCopy = cody;
cody = "foobar";
//male
alert(codyCopy.getGender());
'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');
這允許您使用'new'關鍵字創建具有各自值的Person的多個唯一實例。 所以就行var cody = new Person('Cody', true, 23, 'male');
'this'指的是cody var,在下一行指的是john var。 在你的代碼中'this'指的是你的cody var,因為它在cody對象里面但是沒有必要因為你沒有用自己的值創建新的codys。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.