OOP Javascript - 是“获取属性"吗?方法有必要吗? [英] OOP Javascript - Is "get property" method necessary?
问题描述
给定一个非常简单的 js 对象构造函数及其原型...
Given a very simple js object constructor and its prototype...
function MyTest(name)
{
this.name = name;
}
MyTest.prototype =
{
getName: function()
{
var myName = this.name;
return myName;
},
myMethod: function()
{
//
}
}
现在,在 myMethod 中,使用this.getName"和this.name"有什么区别?
Now, in myMethod, is there any difference between using "this.getName" and "this.name"?
谢谢
推荐答案
取决于 name
是对象还是原始类型(boolean、string、int).
Depends on whether name
is an object nor a primitive (boolean, string, int).
如果name
是一个原语/字符串,并且你使用了this.getName()
,你将无法修改this 的值.name
这样做(假设 this.name = "Billy"
)
If name
is a primitive/ string, and you use this.getName()
, you won't be able to modify the value of this.name
by doing this (assuming this.name = "Billy"
)
this.getName() = "213" //this.name still has a value of "Billy"
如果 name
是一个对象 this.name = { firstName: "Billy", lastName: "Bob"};
this.getName().firstName = "Willy"; //this.name now has a value of { firstName: "Willy", lastName: "Bob"}
这是因为 JavaScript 按值传递基元,但按引用传递对象.
This is due to JavaScript passing primitives by value, but passing objects by reference.
这篇关于OOP Javascript - 是“获取属性"吗?方法有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!