[英]javascript: strict mode and objects
我有一些代码构造了一个对象:
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;
}
我使用w3schools页面作为指南: http : //www.w3schools.com/js/js_objects.asp
一切正常。 然后,我在代码顶部添加了“ use strict”,此功能坏了。 萤火虫报告:这是未定义-this.id = id
我该如何解决?
这意味着您将在不使用new
运算符的情况下调用构造函数。 您需要这样做:
var myGridObjConst = new gridObjConst();
当您在不使用new
运算符的情况下调用该函数时, this
指的是Window,但在严格模式下则不是 ,因此您将出错。
还要注意,您不需要return this;
从构造函数。 this
将自动返回。
如@JoachimSauer所述,在学习JavaScript时,应该考虑使用MDN而不是W3Schools。 在链接到的页面上的任何地方都没有提到原型的事实绝对是荒谬的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.