How to pass methods in javascript?

I often need to pass methods from objects to other objects. However, usually I want this method to be bound to the source object (by application I mean that 'this' must refer to the source object). I know several ways to do this:

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

b) In object A, which was passed to objectB: objectB.assign(function(a,b,c) { that.method(a,b,c) })

c) Outside of both objects: objectB.assign(function(a,b,c) { objectA.method(a,b,c) })

I want to know if there is an easier way to pass methods related to their source objects.

+3
source share
3 answers

You can define the 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);

"myDelegate" "myFunction" "this", "myScope" , myDelegate

+4

, .

0

You can delegate if you want, or simply call an object that does not have a method from a specific scope- method

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

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

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

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

Source: https://habr.com/ru/post/1748723/


All Articles