简体   繁体   English

javascript:严格模式和对象

[英]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 我使用w3schools页面作为指南: 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. 然后,我在代码顶部添加了“ use strict”,此功能坏了。 Firebug reported: this is undefined - this.id = id 萤火虫报告:这是未定义-this.id = id

How do I fix this? 我该如何解决?

That means you are calling your constructor function without the new operator. 这意味着您将在不使用new运算符的情况下调用构造函数。 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. 当您在不使用new运算符的情况下调用该函数时, this指的是Window,但在严格模式下则不是 ,因此您将出错。

Also note that you don't need to return this; 还要注意,您不需要return this; from a constructor function. 从构造函数。 this will be returned automatically. this将自动返回。


As noted by @JoachimSauer, you should look at using MDN instead of W3Schools when learning JavaScript. 如@JoachimSauer所述,在学习JavaScript时,应该考虑使用MDN而不是W3Schools。 The fact that prototypes are not mentioned anywhere on that page you linked to is absolutely ridiculous. 在链接到的页面上的任何地方都没有提到原型的事实绝对是荒谬的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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