can you say this is a right example of Javascript Closure.. Where the places we need to consider avoiding the closures?

自闭症网瘾萝莉.ら 提交于 2019-12-06 11:31:10

Update: Because you probably left out some details in your code, it is difficult to adapt it into something workable without missing the point of your actual code. I do think I understand your underlying problem as you describe it. I hope the following helps.

Suppose the following simple example:

// Constructor function.
function Example() {
    // Method:
    this.method = function() {
        alert("original method");
    }
}

// You would use it like this:
var obj = new Example();
obj.method(); // Calls original method.

To intercept such a method call, you can do this:

function wrap(obj) {
    var originalMethod = obj.method;
    obj.method = function() {
        alert("intercepted call");
        originalMethod.apply(this, arguments);
    }
    return obj;
}

var obj = wrap(new Example());
obj.method(); // Calls wrapped method.

Unfortunately, because method() is defined in the constructor function, not on a prototype, you need to have an object instance to wrap the object.


Answer to original question: The doSomething() function is used as a method on objects created with ActualMethod(). You should use it as a method, not detach it and use it as a function in a different context. Why don't you just call the method directly?

function ClosureTest(){
    var objActual = new ActualMethod();
    // Call method directly, avoid messy apply() calls.
    objActual.doSomething();
    this.ActualTest = function() {
        alert("ActualTest");
    };
}

If you assign a method (a function on some object) to a local variable in Javascript and call it, the context will be different (the value of this changes). If you don't want it to happen, don't do it.

When I want to hook a function, I use the following Function method which is also a fine piece of Closure demonstration:

Function.prototype.wrap = function (wrapper) {
 var __method = this;
 return function() {
  var __obj = this;
  var args = [ __method.bind(__obj) ];
  for(var i=0; i<arguments.length; i++) args.push(arguments[i]);
  return wrapper.apply(__obj, args);
 }
};

Then do something like:

ActualMethod = ActualMethod.wrap(function (proceed, option) {
  // ... handle option
  proceed(); // calls the wrapped function
});

proceed is bound to its initial object, so you can safely call it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!