Skip to content Skip to sidebar Skip to footer

Oop Javascript - Is "get Property" Method Necessary?

Given a very simple js object constructor and its prototype... function MyTest(name) { this.name = name; } MyTest.prototype = { getName: functi

Solution 1:

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).

Solution 2:

Depends on whether name is an object nor a primitive (boolean, string, int).

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"

If name is an object this.name = { firstName: "Billy", lastName: "Bob"};

this.getName().firstName = "Willy"; //this.name now has a value of { firstName: "Willy", lastName: "Bob"}  

This is due to JavaScript passing primitives by value, but passing objects by reference.

Solution 3:

There is no difference. This is not how you implement private vars in JS if that is what you want.

Post a Comment for "Oop Javascript - Is "get Property" Method Necessary?"