函数中的Javascript“new”关键字

Javascript 'new' keyword within function

本文关键字:new 关键字 Javascript 函数      更新时间:2023-09-26
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是否是关键字。

这个函数实际上是由 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 () {}();