DEV Community

Discussion on: The new keyword

Collapse
 
shaneallantaylor profile image
Shane Taylor (he/him)

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!

Collapse
 
tbroyer profile image
Thomas Broyer

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

Thread Thread
 
shaneallantaylor profile image
Shane Taylor (he/him)

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.