I am curious as what else the new
keyword does in the background apart from changing what the this
scope refers too.
For example if we compare using the new
keyword to make a function set properties and methods on an object to just making a function return a new object, is there anything extra that the new object does?
And which is preferred if I don't wish to create multiple objects from the function constructor
var foo2 = function () {
var temp = "test";
return {
getLol: function () {
return temp;
},
setLol: function(value) {
temp = value;
}
};
}();
var foo = new function () {
var temp = "test";
this.getLol = function () {
return temp;
}
this.setLol = function(value) {
temp = value;
}
}();
The firebug profiler tells me using the new keyword is slightly faster (2ms instead of 3ms), on large objects is new still significantly faster?
[Edit]
Another matter is on really large object constructors is having a return at the bottom of the function (It will have a large amount of local functions) or having a few this.bar = ... at the top of the function more readable? What is considered a good convention?
var MAIN = newfunction() {
this.bar = ...
// Lots of code
}();
var MAIN2 = function() {
// Lots of code
return {
bar: ...
}
}();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…