gpt4 book ai didi

javascript - 创建函数后如何编辑函数

转载 作者:行者123 更新时间:2023-11-28 20:59:13 24 4
gpt4 key购买 nike

函数创建后如何编辑?

function foo(a, b) {
this.c = a+b;
}

var bar = new foo(2,3); //result: {'c':5}

//now I would like to create a new function, which is a bit different from the first
foo2 = foo;
foo2.d = a*b; //here I get an error: a is not defined

bar2 = new foo2(3,4);
<小时/>

不,我的意思是结果应该是这样的:

function foo2(a, b) {
this.c = a+b;
this.d = a*b;
}

最佳答案

你无法完全做你想做的事,但有其他方法可以做你想做的事。

function builder(fn, propertyName) {
return function () {
var args = arguments;
this[propertyName] = fn.apply(this, arguments);
this.change = function (otherFn, otherPropertyName) {
return builder(otherFn, otherPropertyName || propertyName);
}
}
}

var Foo = builder(function (a, b) { return a + b; }, "c");

var foo = new Foo(3, 4)

var Foo2 = foo.change(function (a, b) { return a * b; }, "d");

var foo2 = new Foo2(3, 4)

console.log(foo.c, foo2.d) // => 7 12

更好的方法是这样的......

function Foo(a, b) {
var self = this;
this.add = function (name, fn) {
self[name] = fn.call(self, a, b);
}
}

var foo = new Foo(3, 4);
foo.add("c", function (a, b) { return a + b; });
foo.add("d", function (a, b) { return a * b; });

console.log(foo.c, foo2.d) // => 7 1

关于javascript - 创建函数后如何编辑函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11456830/

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