gpt4 book ai didi

javascript:严格模式和对象

转载 作者:行者123 更新时间:2023-11-28 21:00:45 24 4
gpt4 key购买 nike

我有一些构建对象的代码:

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”,这个函数就崩溃了。 Firebug 报告:这是未定义的 - this.id = id

我该如何解决这个问题?

最佳答案

这意味着您正在调用构造函数而不使用 new 运算符。您需要这样做:

var myGridObjConst = new gridObjConst();

当您调用不带 new 运算符的函数时,this 指的是 Window,但在严格模式下它 does not ,因此你的错误。

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

<小时/>

正如 @JoachimSauer 所指出的,在学习 JavaScript 时,您应该考虑使用 MDN 而不是 W3Schools。事实上,在您链接到的页面上的任何地方都没有提到原型(prototype),这绝对是荒谬的。

关于javascript:严格模式和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11118845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com