作用:
1.改变this指向
2.借用其他对象的方法
区别:
call: 传入参数不固定,第一个参数为函数体内部this指向,从第二个参数开始,每个参数依次被传入调用函数。
apply:接收两个参数,第一个参数指定函数体内部this指向,第二个参数为带下标的集合,将集合中的元素作为参数传递给被调用的函数。
调用call与apply,第一参数为 null 时:
// ==================new constructor==============
function P1(){
this.txt = "eeeeeeeee";
}
P1.prototype.log = function(){
console.log(this);
}
var p1 = new P1();
p1.log(); // 正常输出
p1.log.apply(null); //输出window对象
var f1 = p1.log;
f1.call(null); //输出window对象
// ------------strict------------
function P11(){
this.txt = "eeeeeeeee";
}
P11.prototype.log = function(){
"use strict";
console.log(this);
}
var p11 = new P11();
p11.log(); // 正常输出
p11.log.apply(null); //输出 null
var f11 = p11.log;
f11.call(null); //输出 null
// ==================Object.create==============
var P2 = {
txt: "p2p2p2",
log: function(){
console.log(this.txt);
}
}
var p2 = Object.create(P2);
p2.log(); //输出 p2p2p2
p2.log.apply(null); //输出 undfined
var f2 = p2.log;
f2.apply(null); //输出 undfined
// ------------strict------------
var P21 = {
txt: "p2p2p2",
log: function(){
"use strict";
console.log(this.txt);
}
}
var p21 = Object.create(P2);
p21.log(); //输出 p2p2p2
p21.log.apply(null); //输出 undfined
var f21 = p21.log;
f21.apply(null); //输出 undfined