var steve = function() {
this.test = new function() {
console.log('new thing');
}
this.test_not_repeating = function() {
console.log('not repeating');
}
};
steve.prototype.test = function() {
console.log('test');
};
for (var i = 0; i < 100; i++) {
var y = new steve();
}
为什么new
关键字强制要求对函数进行X次计算,而不使用new
关键字则不行?我对javascript的基本理解是,如果你没有把这个函数放在原型上,它将被评估X次,而不管new
关键字是不是。
答案 0 :(得分:3)
这个函数实际上被new运算符称为构造函数,将结果对象赋值给this.test
:
this.test = new function() {
console.log('new thing');
}
此功能仅分配给this.test_not_repeating
,从不调用:
this.test_not_repeating = function() {
console.log('new thing');
}
请记住,使用new
调用函数时不需要括号:
new Constructor;
// Identical to
new Constructor();
new function () {};
// Identical to
new function () {}();