2012-06-20 41 views
0

我有一些代码,构造一个对象:的javascript:严格的模式和对象

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

这一切都工作得很好。然后我在代码的顶部添加了“严格使用”,并且此功能打破了。 Firebug报告:这是不明确的 - this.id = id

我该如何解决这个问题?

+0

你使用'new gridObjConst(...)'还是'gridObjConst(...)'? –

+1

另外:您可能想要寻找[比w3schools更可靠的来源](http://w3fools.com/)。 –

回答

3

这意味着您正在调用您的构造函数,但不包含new运算符。你需要这样做:

var myGridObjConst = new gridObjConst(); 

当你调用而不new操作功能,this指窗口,但在严格的模式下,它does not,因此你的错误。

另请注意,您不需要从构造函数return this;this将自动返回。


正如@JoachimSauer指出,你应该看看学习JavaScript时使用MDN代替W3Schools的的。原型在您链接到的页面上的任何地方都没有提及的事实是非常荒谬的。