gpt4 book ai didi

javascript - Javascript 对象中的函数数组

转载 作者:行者123 更新时间:2023-12-01 01:27:33 25 4
gpt4 key购买 nike

我需要在函数数组中创建一个对象,该对象应该在对象内部调用。但 myObj.myFunctions 在创建后在我的对象内部始终未定义。

这是我的示例代码

var myObj = {
myValue:"My Callback function has been Called",
myFunctions: [this.myCallback,this.myCallback2],
init: function(){
//I need to call this.myFunctions[0...etc] as callback
//this.myFunctions[0]() //<-- Here is the error
console.log(this.myFunctions); //<-- always undefined
},
myCallback:function(){
console.log(this.myValue);
},
myCallback2:function(){
console.log(this.myValue+" Second Callback");
}
}
var createObject = Object.create(myObj);
createObject.init();
 

知道如何创建函数数组作为主对象的属性吗?谢谢

最佳答案

You need to Create a function inside your myFunctions and return those array of callbacks:

方法#1

var myObj = {
myValue:"My Callback function has been Called",
myFunctions: function () { // Assign a function and return those array of callbacks
return [this.myCallback,this.myCallback2];
},
init: function(){
return this.myFunctions();
},
myCallback:function(){
console.log(this.myValue);
},
myCallback2:function(){
console.log(this.myValue+" Second Callback");
}
};

var createObject = Object.create(myObj);
var functions = createObject.init();

console.log(functions); // [f(), f()]
// f for short-term of 'function'

方法#2 - 已经支持使用直接 () 函数调用来获得更简洁的代码

var myObj = {
myValue:"My Callback function has been Called",
myFunctions() {
return [this.myCallback, this.myCallback2]
},
init() {
return this.myFunctions();
},
myCallback(){
console.log(this.myValue);
},
myCallback2(){
console.log(this.myValue+" Second Callback");
}
};

方法 #3 - 使用 ES6 Spread 运算符并将“this”替换为“myObj”

const myObj = {
myValue:"My Callback function has been Called",
myFunctions: () => [myObj.myCallback, myObj.myCallback2],
init: () => myObj.myFunctions(),
myCallback: () => console.log(myObj.myValue),
myCallback2: () => console.log(`${myObj.myValue} Second Callback`)
};

关于javascript - Javascript 对象中的函数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623004/

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