gpt4 book ai didi

javascript - 用于存储行为不符合预期的对象的原型(prototype)

转载 作者:行者123 更新时间:2023-11-28 20:12:13 25 4
gpt4 key购买 nike

我想在原型(prototype)链上创建一个设置对象,用作我的应用程序的查找。我试过这个:

http://jsfiddle.net/7kwXd/3/

var d9l = {};

d9l.aMethod = function() {
//fails here with Cannot read property 'dimension1' of undefined
alert(this.anObject.dimension1);
};

d9l.aMethod.prototype.anObject = {
dimension1 : "x1",
dimension2 : "y1"
};

var testing = d9l.aMethod();

但我只是在构造函数中得到无法读取未定义的属性“dimension1”。不能将原型(prototype)定义为对象吗?

最佳答案

由于 d9l 不是构造对象,因此它的方法不会像您所期望的那样引用 this。要进行验证,请尝试 alert(this) 并查看您得到的结果。

要修复,请执行以下操作:

function d9l() {}
d9l.prototype.aMethod = function() {
alert(this.anObject.dimension1);
};
d9l.prototype.anObject = {
dimension1: "x1",
dimension2: "y1"
};
var testing = (new d9l()).aMethod();

关于javascript - 用于存储行为不符合预期的对象的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19729560/

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