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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…