OOP Javascript - Is “get property” method necessar

2019-07-20 02:00发布

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

3条回答
该账号已被封号
2楼-- · 2019-07-20 02:24

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.

查看更多
叼着烟拽天下
3楼-- · 2019-07-20 02:34

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

查看更多
forever°为你锁心
4楼-- · 2019-07-20 02:36

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

查看更多
登录 后发表回答