javascript call apply and bind

Call(就像打电话,只能一个一个的打)

var obj = { num:2};

var addToThis = function(a){
        return this.num+a;
};

console.log(addToThis.call(obj,3));// 5
// functionname.call(obj,functionarguments);

如果想传入函数多个参数呢,如下

var obj = { num:2};

var addToThis = function(a,b,c){
        return this.num+a+b+c;
};

console.log(addToThis.call(obj,1,2,3));
// functionname.call(obj,functionarguments);

Apply(它可以同时应用于一个数组)

var obj = { num:2};

var addToThis = function(a,b,c){
        return this.num+a+b+c;
};

// console.log(addToThis.call(obj,1,2,3));
// functionname.call(obj,functionarguments);

var arr = [1,2,3];
console.log(addToThis.apply(obj,arr));
var obj = { num:2};
var obj2 = { num:5 };

var addToThis = function(a,b,c){
        return this.num+a+b+c;
};

// console.log(addToThis.call(obj,1,2,3));
// functionname.call(obj,functionarguments);

var arr = [1,2,3];
console.log(addToThis.apply(obj,arr));
console.log(addToThis.apply(obj2,arr));

bind

var obj = { num:2};

var addToThis = function(a,b,c){
        return this.num+a+b+c;
};

var arr = [1,2,3];
var bound = addToThis.bind(obj);

console.dir(bound);
console.log(bound(1,2,3));// 8

你可能感兴趣的:(javascript call apply and bind)