gpt4 book ai didi

javascript - 将回调分配给对象内部的对象

转载 作者:行者123 更新时间:2023-11-29 16:13:27 26 4
gpt4 key购买 nike

我正在尝试通过将变量名称及其对应的回调放入一个易于迭代的对象中来重构一段代码,该代码作用于 variables 数组中的每个变量.问题是 variables[0].callback 在调用 Foo.bar(data) 时以 undefined 结束。整个对象的功能需要保留在对象本身中。

到目前为止,我唯一的解决方案是在将函数分配给回调变量时定义函数,但这并不理想,因为回调本身无法访问所需的变量。

...
{name: "x", callback: function() {...}},
...

期望的功能:

console.log(Foo.variables[0].callback != undefined) //true
Foo.bar(); //Will print "y"

我是不是错过了什么傻事?还是我应该使用另一种模式来解决这个特定问题?

感谢您的帮助!

var Foo = {

variables: [
{name: "x", callback: this.funX},
{name: "y", callback: this.funY},
{name: "z", callback: this.funZ}
],


//For this example, data could be the following object
// data = {x: 0, y: 1, z: 0};
bar: function(data) {

this.variables.forEach(function(elem) {
if(data[elem.name] == 1)
elem.callback();
});

},

funX: function() {
console.log(this.variables[0].name);
},

funY: function() {
console.log(this.variables[1].name);
},

funZ: function() {
console.log(this.variables[2].name);
}
}

有点相关:

javascript: call function inside object, from a callback function

最佳答案

LIVE DEMO

引用:

//For this example, data could be the following object
// data = {x: 0, y: 1, z: 0};

所以让我们使用 Foo.bar({x: 0, y: 1, z: 0});

例子:

var Foo = {

variables: [
{name: "x", callback: "funX"},
{name: "y", callback: "funY"},
{name: "z", callback: "funZ"}
],
bar: function(data) {
var that = this; // this (Foo) reference!
that.variables.forEach(function(el, i, arr) {
if(data[el.name] == 1){
var fn = arr[i].callback; // funY
that[fn](); // "y" (cause that's exactly what funY does!!)
}
});
},
funX: function() {
console.log(this.variables[0].name);
},
funY: function() {
console.log(this.variables[1].name);
},
funZ: function() {
console.log(this.variables[2].name);
}
};


Foo.bar({x: 0, y: 1, z: 0});

关于javascript - 将回调分配给对象内部的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21423534/

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