I had some code that constructed an object:
function gridObjConst(id, itemName, itemPrice, itemListPrice, width, height, imgName) {
this.id = id;
this.itemName = itemName;
this.itemPrice = itemPrice;
this.itemListPrice = itemListPrice;
this.width = width;
this.height = height;
this.imgName = imgName;
return this;
}
I used the w3schools page as a guide: http://www.w3schools.com/js/js_objects.asp
It all worked fine. Then I added “use strict” to the top of my code and this function broke. Firebug reported: this is undefined – this.id = id
How do I fix this?
That means you are calling your constructor function without the
newoperator. You need to do this:When you call the function without the
newoperator,thisrefers to the Window, but in strict mode it does not, hence your error.Also note that you don’t need to
return this;from a constructor function.thiswill be returned automatically.As noted by @JoachimSauer, you should look at using MDN instead of W3Schools when learning JavaScript. The fact that prototypes are not mentioned anywhere on that page you linked to is absolutely ridiculous.