OOP Javascript - Is “get property” method necessar

2019-07-20 01:44发布

问题:

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

回答1:

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.



回答2:

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



回答3:

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