Skip to content

Instantly share code, notes, and snippets.

@shuhrat
Last active December 25, 2018 12:05
Show Gist options
  • Save shuhrat/c696c928aa69b49e3952e61fc53639bb to your computer and use it in GitHub Desktop.
Save shuhrat/c696c928aa69b49e3952e61fc53639bb to your computer and use it in GitHub Desktop.

Объясните, для чего предназначена и каким образом работает следующая функция:

function bind(method, context) {
    var args = Array.prototype.slice.call(arguments, 2);
    return function() {
        var a = args.concat(Array.prototype.slice.call(arguments, 0));
        return method.apply(context, a);
    }
}

Данная функция будет использоваться, если есть несколько объектов, имеющих метод apply, или если они реализуют интерфейс в котором есть этот метод. Она позволяет создавать функции, вызывающие метод apply у передаваемого объекта, передавая в него context и массив аргументов, переданных в bind кроме method и context и в созданную функцию в соответственном порядке.

вот примитивный пример

function bind(method, context) {
    var args = Array.prototype.slice.call(arguments, 2);
    return function() {
        var a = args.concat(Array.prototype.slice.call(arguments, 0));
        return method.apply(context, a);
    }
}

let a=()=>{};

a.apply=function (context,args) {
    switch (context) {
        case "log":
            console.log(args);
            break;
        default:
            break
    }
};

let b=bind(a,"log",1,2);

b(3,4);
b(5,6);

Выведет: [ 1, 2, 3, 4 ] [ 1, 2, 5, 6 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment