I have a JavaScript object that has multiple methods:
var actualObject = {
foo: function(){},
bar: function(){},
…
}
However, the actual object that I want people to use is proxy
. It should forward all its calls to actualObject
. The simplest way of doing that would be simply assigning actualObject
to 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. 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?
Have the proxy
prototype to be actualObject
then define the function in proxy
:
var proxy = Object.create(actualObject);
proxy.bar = function(arguments) {
console.log('do something beforehand');
actualObject.bar(arguments);
console.log('do something afterward');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.