Javascript:如何在不复制但通过链接的情况下将另一个对象B的方法混入到对象A中? [英] Javascript: How can I mix in methods of another Object B to my Object A without copying but with linking?

查看:92
本文介绍了Javascript:如何在不复制但通过链接的情况下将另一个对象B的方法混入到对象A中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个对象A:

If I create an Object A:

let A = {};

并想混入另一个对象B中的方法:

And want to mix in methods from another Object B:

let B = {
    foo() {
        alert("Boo!");
    }
};

通常我会打电话给

Object.assign(A, B);

然后我更改函数foo:

Then I change my function foo:

Object.assign(B, {
    foo() {
        alert("Hooray!");
    }
});

之后我叫foo:

A.foo(); // Actual output: "Boo!"

但我希望输出为万岁!". 到目前为止,我发现Object.assign仅复制目标中的方法,但未链接它们. 关于继承和组合,我在这里找到了有用的博客文章:为什么原型继承很重要,大多数在这里占主导地位:了解原型,授权与合作;组成

But I want that output to be "Hooray!". So far I found out, that Object.assign only copies methods in the target, but it doesn't link them. About inheritance and composition I found useful blogposts here:Why prototypical inheritance matters and most dominantly here: Understanding Prototypes, Delegation & Composition

我想在对象中混合一个方法,而不是复制这些方法,而我想对混合函数的定义赋值.

I want to mix a method in an Object, but not copy the methods, much more rather I want an assignment to the definition of the mixed in function.

这怎么可能?

推荐答案

原型继承助您一臂之力:

Prototype inheritance comes to your rescue:

var A = Object.create(B);
A.foo();
B.foo = …;
A.foo(); // something else

当然,这不再严格来说是混合",您只能通过原型链接从另一个对象继承(尽管您可以构建继承链).

Of course, this is not strictly a "mixin" any more, and you can only inherit via the prototype link from one other object only (though you can build an inheritance chain).

如果您希望将多个独立的对象混合到现有的A对象中,那么这是不可能的.抱歉.

If you are looking to mix multiple independent objects into your existing A object, then that is not possible. Sorry.

这篇关于Javascript:如何在不复制但通过链接的情况下将另一个对象B的方法混入到对象A中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆