obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);
两者作用一致,都是把obj(即this)绑定到thisObj,这时候thisObj具备了obj的属性和方法。或者说thisObj『继承』了obj的属性和方法。绑定后会立即执行函数。
两者的不同之处:传递参数不同,call已正常参数传递,apply传参数的形式是以数组的形式传递。
bind():把obj绑定到thisObj,这时候thisObj具备了obj的属性和方法。与call和apply不同的是,bind绑定后不会立即执行。obj.bind(thisObj, arg1, arg2, ...);bind()只是起到绑定作用并不执行,只有执行才会触发obj.bind(thisObj, arg1, arg2, ...)();
function add(a,b) { this.num1 = a; this.num2 = b; return num1 + num2; } function sub(a,b) { this.num1 = a; this.num2 = b; return num1 - num2; } console.log( add(3,5) );//8 console.log( sub(5,3) );//2 console.log( sub.call(add,5,3) );//把sub()的方法绑定到add()方法上。实现了sub()方法。 console.log( sub.apply(add,[5,3]) );//2 console.log( add.call(sub,5,3) );//8 console.log( add.apply(sub,[5,3]) );//8
在对象中的使用:
var person = { sex: "boy", action: function() { console.log( this.sex+" good good study,day day up!" ); //return this.sex+" good good study,day day up!"; } } console.log(person.action);//f() {} var p1 = person.action; p1();//undefined good good study,day day up! p1.call(person);//boy good good study,day day up! p1.apply(person);//boy good good study,day day up! //使用call(),apply();被调用的对象的方法能够访问对象的属性,赋给调用者。同样可以传递参数。 var person1 = { sex: "boy", action: function(a,b) { console.log( this.sex+" good good study,day day up!"+"age: "+a+"job: "+b ); //return this.sex+" good good study,day day up!"; } } console.log(person1.action);//f() {} var p1 = person1.action; p1(23,"IT");//undefined good good study,day day up!age: 23job: IT p1.call(person1,23,"IT");//boy good good study,day day up!age: 23job: IT p1.apply(person1,[23,"IT"]);//boy good good study,day day up!age: 23job: IT
利用call()或者apply()方法可对对象等使用其他数据类型的方法;(可以理解为把谁的方法添加到调用的对象上)
var a = { a: 1, b: "assassin", c: 2 } //console.log(a.slice());//TypeError a.slice is not a function console.log( Array.prototype.slice.call(a) );//[]
可以扩展到自己的方法中:
var animate = { name: "animate", fnAn: function() { console.log("animate..."); } } var pp = {}; animate.fnAn.call(pp);//speak... animate.fnAn.call(pp);//speaking
通过call和apply,我们可以实现对象继承。
function People() { this.age = 23; this.name = "assassin"; } var people = {}; console.log( People);//ƒ People() {//...} console.log( people );//{} //People.call(people); People.apply(people); console.log(people);//{age: 23, name: "assassin"} //同样可以传递参数: function People1(age,name) { this.age = age; this.name = name; } var people1 = {}; console.log( People1);//ƒ People(age,name) {//...} console.log( people1 );//{} //People.call(people,23,"assassin"); People1.apply(people1,[23,"assassin"]); console.log(people1);//{age: 23, name: "assassin"}
bind();方法使用详解
function fn1(a,b) { console.log( a*b ); } function fn2(a,b) { console.log( a/b ); } fn1(6,3);//18 fn1.bind(fn2,6,3);//并没有执行 fn1.bind(fn2,6,3)();//18