call:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
1.定义
调用一个对象的一个方法,以另一个对象替换当前对象。
2.说明
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
-
- 在js的函数上可以使用call方法来改变函数中的this指向
- call里面的第一个参数会改变调用call方法的函数内的this
- 不过第一个参数到达函数内部后会自动转成对象形式变成this
- call里面的第二个参数及之后则对应调用call方法的函数的第一个参数及之后
3.thisObj的取值有以下4种情况
-
- 不传,或者传null,undefined, 函数中的this指向window对象
- 传递另一个函数的函数名,函数中的this指向这个函数的引用
- 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean
- 传递一个对象,函数中的this指向这个对象
4.代码示例
4.1.js的函数上可以使用call方法来改变函数中的this指向
function a(){ console.log(this); //输出函数a中的this对象 } function b(){} var c={name:"call"}; //定义对象c a.call(); //window a.call(null); //window a.call(undefined); //window a.call(1); //Number a.call(''); //String a.call(true); //Boolean a.call(b); //function b(){} a.call(c); //Object
4.2.通过call实现两个函数之间的继承
function class1(){ this.name=function(){ console.log("我是class1内的方法"); } } function class2(){ class1.call(this); //此行代码执行后,当前的this指向了class1(也可以说class2继承了class1) } var f=new class2(); f.name(); //调用的是class1内的方法,将class1的name方法交给class2使用
4.3.通过call实现两个函数之间的替换
function eat(x,y){ console.log(x+y); } function drink(x,y){ console.log(x-y); } eat.call(drink,3,2); //输出:5 //这个例子中的意思就是用 eat 来替换 drink,eat.call(drink,3,2) == eat(3,2) ,所以运行结果为:console.log(5); //注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。
4.4.通过call实现两个函数之间的方法和属性的继承
function Animal(){ this.name="animal"; this.showName=function(){ console.log(this.name); } } function Dog(){ this.name="dog"; } var animal=new Animal(); var dog=new Dog(); animal.showName.call(dog); //输出:dog //在上面的代码中,我们可以看到Dog里并没有showName方法,那为什么(this.name)的值是dog呢? //关键就在于最后一段代码(animal.showName.call(dog)),意思是把animal的方法放到dog上执行,也可以说,把animal 的showName()方法放到 dog上来执行,所以this.name 应该是 dog。
//继承 function Animal(name){ this.name=name; this.showName=function(){ console.log(this.name); } } function Dog(name){ Animal.call(this,name); } var dog=new Dog("Crazy dog"); dog.showName(); //输出:Crazy dog //Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么Dog就能直接调用Animal的所有属性和方法。
参考---https://blog.csdn.net/weixin_43732485/article/details/121999936