-1

Hi would like to create a function that takes one argument (a function) and proxies the function:

function proxyFunc(func) {
  console.log("Proxying ", func.name);
  var proxied = func;
  func = function() {
   console.log("Calling proxied ", func.name);
   return proxied.apply(this, arguments);
  };
}

Unfortunately the proxying does not work. I already figured out that the assignment of the proxy function to the original function is the problem, but I don't know how to make it work:

func = function() { ... }
2
  • You need to return func, otherwise your proxyFunc has no effect. Commented Nov 20, 2011 at 21:02
  • I want to intercept calls to methods Commented Nov 20, 2011 at 21:03

1 Answer 1

4

Are you looking for this?

function proxyFunc(original) {
    console.log("Proxying ", original.name);
    return function() {
       console.log("Calling proxied " + original.name);
       return original.apply(this, arguments);
    };
}

For what you're doing, this will help:

function proxyMember(obj, member) {
    var original = obj[member];
    console.log("Proxying ", member);
    obj[member] = function() {
       console.log("Calling proxied " + member);
       return original.apply(this, arguments);
    };
}

proxyMember(obj, "foo");
Sign up to request clarification or add additional context in comments.

4 Comments

This can be used as Object.func1 = proxyFunc(Object.func1) but I would like to skip the assignment
@nrabinowitz: Note that you can set name by using var f = function foo(x) { ... }, instead of setting it manually.
@Erik: You can't. Javascript doesn't pass arguments like that.
@Eric - huh, never knew that. But note that MDN marks this as non-standard, and it isn't part of the ECMAScript spec. That page also explains why my approach didn't work, as the property (in implementing interpreters) is read-only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.