Front-end focused, forever in pursuit CSS solutions and finding balance. I dig the React community and find kinship with lifelong learners. New 'favorite emoji' every other week. Current fave: 🏄
Location
Los Angeles
Work
Lead Instructor and Senior Software Engineer at Codesmith
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:
functioncreateCar(color,speed){this.color=color;this.speed=speed;return'Cars are cool!';}createCar.prototype.go=function(){console.log('I prefer to drive '+this.speed+'.');}constmyCar=newcreateCar('red','fast');myCar.go();console.log('myCar is',myCar);constnewCar=newcreateCar('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!
Front-end focused, forever in pursuit CSS solutions and finding balance. I dig the React community and find kinship with lifelong learners. New 'favorite emoji' every other week. Current fave: 🏄
Location
Los Angeles
Work
Lead Instructor and Senior Software Engineer at Codesmith
functioncreateCar(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+'.');}constmyCar=newcreateCar('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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hey Thomas!
From my testing, it looks like
new
will still return the object stored at thethis
property from the function being altered bynew
.For example:
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.
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.