gpt4 book ai didi

javascript - 原型(prototype)中的对象

转载 作者:行者123 更新时间:2023-12-02 14:34:14 25 4
gpt4 key购买 nike

我已经在原型(prototype)中创建了一个对象,并且尝试使用 this 从构造函数访问变量,但警报正在返回 undefined .

构造函数

function Example() {
this.param1 = 'test';
}

原型(prototype)

Example.prototype = {
constructor: Example,
obj: {
sample:function() {

alert(this.param1); // error undifined

}
}
};

实例化

var o = new Example();
o.obj.sample();

如有任何建议,我们将不胜感激。

最佳答案

你可以这样做

function Example() {
this.param1 = 'test';
}
Example.prototype = {
constructor: Example,
obj: {
sample:function(){
alert(this.param1); // error undifined
}
}
};

var o = new Example();
o.obj.sample.call(o); // <--- I use "call" to supply the context. In this case, the context would be "o"
// or
o.obj.sample.bind(o)(); // or "bind" the context, in this case "o"

关于javascript - 原型(prototype)中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37580456/

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