简体   繁体   中英

javascript: strict mode and objects

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 new operator. You need to do this:

var myGridObjConst = new gridObjConst();

When you call the function without the new operator, this refers 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. this will 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM