re: The new keyword VIEW POST

FULL DISCUSSION
 

Correct me if I'm wrong, but if the function returns a value, the new invocation will actually return that value rather than the this. I have no idea why it works that way though, as it's really unintuitive, but I think one had to decide what to do in such case and ignoring the return value would have been weird too (throwing an error? Well, why not…)

 

Hey Thomas!

From my testing, it looks like new will still return the object stored at the this property from the function being altered by new.

For example:

function createCar(color, speed) {
  this.color = color;
  this.speed = speed;
  return 'Cars are cool!';
}

createCar.prototype.go = function () {
  console.log('I prefer to drive ' + this.speed + '.');
}

const myCar = new createCar('red', 'fast');
myCar.go();
console.log('myCar is', myCar);

const newCar = new createCar('green', 'slow');
console.log('newCar is', newCar);

Both of the console logs above return the object stored at this during the execution of createCar.

Good question though! Let me know if you see any issues with my logic - would love to know more!

 

It's because you return a string. If you returned an object, it would be used instead.

See also developer.mozilla.org/en-US/docs/W...

Thomas, you are sooooo right.

function createCar(color, speed) {
  this.color = color;
  this.speed = speed;
  return { motto: 'Cars are cool' };
}

createCar.prototype.go = function () {
  console.log('I prefer to drive ' + this.speed + '.');
}

const myCar = new createCar('red', 'fast');
console.log('myCar is', myCar); // will log the object with the 'motto' key :( :(

Thank you for highlighting this oddity. I'll be updating the article and including this in an upcoming post about things to be cautious of with the new keyword.

code of conduct - report abuse