开发者

How can I pass methods in javascript?

开发者 https://www.devze.com 2023-01-02 16:54 出处:网络
I often need to pass methods from objects into other objects. However I usually want the method to be attached to the original object (by attached I mean \'this\' should refer to the original object).

I often need to pass methods from objects into other objects. However I usually want the method to be attached to the original object (by attached I mean 'this' should refer to the original object). I know a few ways to do this:

a) In the object constructor: ObjectA = function() { var that = this; var method = function(a,b,c) { that.abc = a+b+c }}

b) In objectA which has been passed objectB: objectB.assign(function(a,b,c) { that.method(a,b,c) })

c) Outside both objects: objectB.assign(function(a,b,c) { ob开发者_运维技巧jectA.method(a,b,c) })

I want to know if there is a simpler way to pass methods attached to their original objects.


You can define a "createDelegate" method for all functions:

Function.prototype.createDelegate = function(scope) {
    var method = this;
    return function() {
        return method.apply(scope, arguments);
    }
}

And then use like:

var myDelegate = myFunction.createDelegate(myScope);

calling "myDelegate" will execute "myFunction" with "this" pointing to "myScope" and the same arguments as passed to myDelegate


As long as you call the other method with its appropriate owner object, this will always refer to the correct owner.


You can delegate if you like, or just call the object that lacks the method from the defined method scope-

instance.method.call(Other-Object/*,argument,...*/)

For example, if Array has a filter method, you can call it as if it were a method of a node list object.

var list=document.getElementsByTagName('p'), a=[], 

list= a.filter.call(list,function(itm){return itm.className=='sidebar'});
0

精彩评论

暂无评论...
验证码 换一张
取 消