gpt4 book ai didi

javascript - 如何为所有对象属性制作原型(prototype)函数?

转载 作者:行者123 更新时间:2023-11-29 21:36:40 24 4
gpt4 key购买 nike

我有一个函数对象,我想为所有这些属性制作另一个函数的原型(prototype)。

例子:

var test = function(num) {
return num * num / (num/4);
}

var obj = {
item1: item1, //this is a function already setted.
item2: item2, //this is a function already setted.
item3: item3 //this is a function already setted
}

我想要的是这样的:obj.item1().test() 没有在每个函数中设置 this.test

最佳答案

你的测试函数

return num * num / (num/4);

在我看来完全等同于 num * 4

无论如何,您评论中给出的示例 itemX 返回一个数字。能够对数字调用函数 test 的唯一方法是将其添加到 Number 原型(prototype),有些人会说这是个坏主意:

Object.defineProperty(Number.prototype, 'test', { value: function () {
return this * this / (this/4);
});

如果您希望能够将 test 从调用结果链接到 obj.itemX,则后者需要返回 this,不是 this.num:

var itemX = function(val) {this.num = val; return this};

现在你只需要在obj上放置一次修改过的test:

var obj = {
item1: item1, //this is a function already set.
item2: item2, //this is a function already set.
item3: item3, //this is a function already set.

test: function() { return test(this.num); }
};

> obj.item1(22).test()
< 88

How can I make a prototype function to all my object properties?

如果您指的是 test,则这不是原型(prototype)函数。它只是对象上的一个普通的旧方法。要添加它,只需将它添加到对象上,就像上面所做的那样。

关于javascript - 如何为所有对象属性制作原型(prototype)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668297/

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