简体   繁体   中英

Javascript 'new' keyword within function

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();
}

Why does the new keyword force the function to be evaluated X times, where not using the new keyword doesn't? My rudimentary understanding of javascript is, if you do not put the function on the prototype it will be evaluated X times regardless of the new keyword or not.

This function is actually called as a constructor by the new operator, assigning the resulting object to this.test :

this.test = new function() {
    console.log('new thing');
}

This function only gets assigned to this.test_not_repeating , it's never called:

this.test_not_repeating = function() {
    console.log('new thing');
}

Remember that functions do not need parenthesis when called with new :

new Constructor;

// Identical to
new Constructor();
new function () {};

// Identical to
new function () {}();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM