举例
//定义一个函数
function add(x, y) {
return x + y;
}
//用call 来调用
function myAddCall(x, y) {
//调用 add 方法 的 call 方法
return add.call(this, x, y);
}
//apply 来调用
function myAddApply(x, y) {
//调用 add 方法 的 applly 方法
return add.apply(this, [x, y]);
}
console.log(myAddCall(10, 20)); //输出结果30
console.log(myAddApply(20, 20)); //输出结果40
eg2:
function isArray1(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
let o1 = {
a: '1'
};
console.log(isArray1(o1))
console.log(o1.toString() === '[object Array]')
add: bind
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
return this.a + this.b + c + d;
}
};
Function.prototype.bind = Function.prototype.bind || function(context) {
var that = this;
return function() {
// console.log(arguments); // console [3,4] if ie<6-8>
return that.apply(context, arguments);
}
}
window.a = window.b = 0;
var func = obj.getCount.bind(obj);
console.log(func(3, 4)); // 10
eg3:
var x = 0;
function test(option) {
if(option){
console.log(option );
console.log(option.x);
console.log(this)
}
}
var o = {};
o.x = 1;
o.m = test;
o.m.apply(); //0
o.m.apply(o,[{x:2}]); //1
apply与call 实际是改变被执行函数的上下文;
补充:
a.call(b);
a.apply(b,[])
apply与call 实现函数的继承
本质是实现 a 对象到b对象的继承 ,既 b继承a / b包含了a 的所有参数和函数 并传参数给a 参数形式不同,在对象b的作用域下 执行了函数a,