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()
{
//
}
}
Now, in myMethod, is there any difference between using "this.getName" and "this.name"?
Thanks
Depends on whether
name
is an object nor a primitive (boolean, string, int).If
name
is a primitive/ string, and you usethis.getName()
, you won't be able to modify the value ofthis.name
by doing this (assumingthis.name = "Billy"
)If
name
is an objectthis.name = { firstName: "Billy", lastName: "Bob"};
This is due to JavaScript passing primitives by value, but passing objects by reference.
There is no difference. This is not how you implement private vars in JS if that is what you want.
Using the function is slightly slower, but allows you to change how it works in the future (or to do so in another object type that inherits from this one).