javascript-call和javascript-apply的用法,实现javascript-bind

  • function.prototype.call和 function.prototype.apply的作用:
    1. 改变this指向
    1. 借用借他对象的方法
  • function.prototype.bind 函数用于指定函数内部this的指向

  • 实现原理:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    function.prototype.bind = function () {
    var self = this; //保存原函数
    var args = [].slice.call(arguments);
    var context = args.shift();
    return function () {
    var argsArr = [].slice.call(arguments);
    return self.apply(context, args.concat(argsArr));
    }
    }
    var bindTest = function (age, grade) {
    console.log(this.name);
    console.log([age, grade]);
    }.bind({name: 'Jack'}, 22);
    bindTest(95.0);