this总是指向调用某个方法的对象,而使用call()和apply()方法时,就可以改变this的指向。
用法:A.call( B,arg1,arg2 )
解释:就是把A的函数放到B中运行,arg1 和arg2 是A方法的参数。
apply()和call()差不多,只不过apply第二个参数必须传入的是一个数组,而call 第二个参数可以是任意类型
function add (x, y) {
console.log (x + y);
}
function minus (x, y) {
console.log (x - y);
}
add.call (minus , 1, 1); //2
其实就是用 add 来替换 minus ,add.call(minus ,1,1) == add(1,1) ,所以运行结果为2
注意:js 中的函数其实是对象,函数名是对 Function 对象的引用
用call来实现继承,用this可以继承myfunc1中的所有方法和属性。
function myfunc1(){
this.name = 'Leslie';
this.myTxt = function(txt) {
console.log( 'i am',txt );
}
}
function myfunc2(){
myfunc1.call(this);
}
let myfunc3 = new myfunc2();
myfunc3.myTxt('hh'); // i am hh
console.log (myfunc3.name); // Leslie