简体   繁体   English

JavaScript对象装饰器

[英]JavaScript Object Decorator

I have a JavaScript object that has multiple methods: 我有一个具有多种方法的JavaScript对象:

var actualObject = {

    foo: function(){},
    bar: function(){},
    …

}

However, the actual object that I want people to use is proxy . 但是,我希望人们使用的实际对象是proxy It should forward all its calls to actualObject . 它应该将其所有调用转发给actualObject The simplest way of doing that would be simply assigning actualObject to proxy . 最简单的方法是将actualObject分配给proxy

proxy = actualObject;

However, for some methods, I want proxy to have additional functionality. 但是,对于某些方法,我希望代理具有其他功能。

proxy.bar = function(arguments) {
    console.log('do something beforehand');
    actualObject.bar(arguments);
    console.log('do something afterward');
}

The problem is, if proxy and actualObject are the same, this overridden bar method will cause a recursion. 问题是,如果proxyactualObject相同,则此覆盖的bar方法将导致递归。 Thus my question: What is the most "idiomatic" way of cloning a JavaScript object but overriding certain methods in a way that would allow calling the original methods from within the overriding ones? 因此,我的问题是:克隆JavaScript对象但以允许从覆盖对象中调用原始方法的方式覆盖某些方法的最“惯用”方法是什么?

Have the proxy prototype to be actualObject then define the function in proxy : 有一个proxy原型是actualObject然后在proxy定义函数:

var proxy = Object.create(actualObject);

proxy.bar = function(arguments) {
    console.log('do something beforehand');
    actualObject.bar(arguments);
    console.log('do something afterward');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM