1
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.

7
  • 4
    Is that all of the code? I can see immediately that you're missing a closing brace in the constructor function. Probably off-topic from your question, but still, it stands out. Commented Dec 9, 2015 at 16:40
  • the closing bracket is in the line steve.prototype.test = function () { console.log('test'); }; The styling is just bad Commented Dec 9, 2015 at 16:40
  • @Safari no? That's closing that anonymous function. It's still not closing the constructor (steve) function. Commented Dec 9, 2015 at 16:41
  • ohh true. my mistake Commented Dec 9, 2015 at 16:42
  • fixed the missing brace Commented Dec 9, 2015 at 16:42

1 Answer 1

3

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 () {}();
Sign up to request clarification or add additional context in comments.

2 Comments

which is better ? assigning a function without new or putting the function on the prototype?
@gh9: if the function doesn't need the benefit of the enclosing scope, it's usually best to put it on the prototype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.