gpt4 book ai didi

javascript - 带有 this/bind 的 JS 原型(prototype)范围

转载 作者:行者123 更新时间:2023-11-28 16:25:04 26 4
gpt4 key购买 nike

我有以下代码,可以在 JavaScript 中创建一个对象。它使用原型(prototype)来定义函数和构造函数。

function objectClass(){
this.variables = new Array();
}

objectClass.prototype =
{
contructor: objectClass,

setInfo: function(){
$.ajax({
url: "info.json",
success: function(){
//for each json element returned...
this.variables.push(json[i]);
}
});
}
getInfo: function(){
return this.variables;
},
}

这是我正在尝试做的类似示例。当我调用 obj.getInfo() 时,我需要能够返回变量数组。它总是抛出错误。我相信这是因为“this”指的是ajax成功函数的范围。

关于如何让它引用对象变量有什么想法吗?

最佳答案

这是正确的,this 值不会自动传递,因此不会设置到实例。要强制执行此操作,您可以使用 $.ajax 接受的 context 属性:

$.ajax({
context: this, // `this` is the instance here

这会将成功回调中的 this 值设置为您指定的值。

关于javascript - 带有 this/bind 的 JS 原型(prototype)范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8300241/

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