gpt4 book ai didi

javascript - jQuery 扩展多个对象具有相同的功能

转载 作者:行者123 更新时间:2023-11-28 00:56:38 25 4
gpt4 key购买 nike

所以我使用 $.extend 来组合多个组件(对象)。其中一些组件具有相同键的功能。我希望最终的扩展对象具有相同的键,但让它指向一个函数,该函数依次调用所有合并组件的函数版本。

所以它看起来像这样:

var a = { foo: function() { console.log("a"); } };
var b = { foo: function() { console.log("b"); } };
var c = {}; // Doesn't have foo

var d = $.extend({}, a, b, c);
var e = $.extend({}, a, c);
var f = $.extend({}, c);

d.foo(); // Should call function() { console.log("a"); console.log("b"); }
e.foo(); // Should call function() { console.log("a"); }
f.foo(); // Should call function() {}

有没有一种实用的方法可以做到这一点?我只想对一组特定的键执行此操作,因此我只想将这些特定键的功能合并在一起,并让扩展中的顺序覆盖其他任何内容。

希望这是有道理的:S

最佳答案

注意

f.foo(); // Should call function() {}

object c 似乎没有属性 foo 。调用 f.foo() 返回 TypeError: undefined is not a function 。不确定是否需要将 foo 函数添加到扩展 f 对象,或从匿名函数返回对象 c(空对象)?在下面的代码中,foo 函数添加到扩展f 对象中。

jquery $.Callbacks() 用于在 $.each()

处添加具有 foo 属性的函数

尝试

var a = { foo: function() { console.log("a"); } };
var b = { foo: function() { console.log("b"); } };
var c = {}; // Doesn't have foo

//d.foo();
// Should call function() { console.log("a"); console.log("b"); }
//e.foo();
// Should call function() { console.log("a"); }
//f.foo();
// Should call function() {}

var callbacks = $.Callbacks();
var arr = [], d, e, f;
$.each([a,b,c], function(k, v, j) {
var j = [a,b,c];
// filter objects having `foo` property
if (v.hasOwnProperty("foo")) {
arr.push([v, v.foo]);
if (arr.length > 1) {
callbacks.add(arr[0][1], arr[1][1]);
// `add` `foo` properties to `callbacks`
// `fire` both `callbacks` when `object.foo` called
j[k -1].foo = callbacks.fire;
d = $.extend({}, j[k - 1])
} else {
// `else` extend original data (`fn`, `object`)
// contained within object
e = $.extend({}, j[k + 1]);
f = $.extend({}, j[++k + 1]);
}
}
});

d.foo(); // `a` , `b`
e.foo(); // `b`
console.log(f); // `Object {}`
f.foo() // `TypeError: undefined is not a function`

jsfiddle http://jsfiddle.net/guest271314/3k35buc1/

参见jQuery.Callbacks()

关于javascript - jQuery 扩展多个对象具有相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26150196/

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