gpt4 book ai didi

javascript - 将定义的函数分配给javascript中的对象属性

转载 作者:行者123 更新时间:2023-11-30 18:30:06 25 4
gpt4 key购买 nike

我在 javascript 中有一个对象和一些已经定义的函数。但是我如何将这些功能分配给对象属性。我尝试了不同的方式。但没有希望.. 下面给出了片段

// object
var func = {
a : '',
b : ''
};

// methods
var test1 = function(i) { console.log(i); }
var test2 = function(i) { console.log(i*100); }

我需要将 test1 分配给 a,将 test2 分配给 b。我试过这样。

var func = {
a : test1(i),
b : test2(i)
};

显然 i not defined 正在抛出错误。除了下面给出的 sinppet 之外,还有其他解决方案吗。

var func = {
a : function(i) { test1(i); },
b : function(i) { test2(i); }
};

最佳答案

这会满足您的要求:

var test1 = function(i) { console.log(i); }
var test2 = function(i) { console.log(i*100); }
var func = {
a: test1,
b: test2
}

但不是很好的风格。

这可能会更好:

function exampleClass () {}
exampleClass.prototype.a = function(i) { console.log(i); };
exampleClass.prototype.b = function(i) { console.log(i*100); };

var exampleObject = new exampleClass();

关于javascript - 将定义的函数分配给javascript中的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9903407/

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