Javascript automatic getter/setters (John Resig Book)

前端 未结 8 643
陌清茗
陌清茗 2020-12-14 03:02

I\'m reading \"Pro Javascript Techniques\" from John Resig, and I\'m confused with an example. This is the code:

// Create a new user object that accepts an          


        
8条回答
  •  不思量自难忘°
    2020-12-14 03:19

    I think it's best not to use the new keyword at all when working in JavaScript.

    This is because if you then instantiate the object without using the new keyword (ex: var user = User()) by mistake, *very bad things will happen...*reason being that in the function (if instantiated without the new keyword), the this will refer to the global object, ie the window...

    So therefore, I suggest a better way on how to use class-like objects.

    Consider the following example :

    var user = function (props) {
        var pObject = {};
        for (p in props) {
            (function (pc) {
                pObject['set' + pc] = function (v) {
                    props[pc] = v;
                    return pObject;
                }
                pObject['get' + pc] = function () {
                    return props[pc];
                }
            })(p);
        }
        return pObject;
    }
    

    In the above example, I am creating a new object inside of the function, and then attaching getters and setters to this newly created object.

    Finally, I am returning this newly created object. Note that the the this keyword is not used anywhere

    Then, to 'instantiate' a user, I would do the following:

    var john = user({name : 'Andreas', age : 21});
    john.getname(); //returns 'Andreas'
    john.setage(19).getage(); //returns 19
    

    The best way to avoid falling into pitfalls is by not creating them in the first place...In the above example, I am avoiding the new keyword pitfall (as i said, not using the new keyword when it's supposed to be used will cause bad things to happen) by not using new at all.

提交回复
热议问题