likes
comments
collection
share

Javascript 关于call() 的快速理解方法

作者站长头像
站长
· 阅读数 18

理解call()函数前, 首先要了解一下this的指向问题

this指向:

1.指向window:

var name = '小红' 
function foo () { 
    console.log(this.name) //小红 
} 
foo() //直接调用方法指向的就是window

2.指向直接调用者:

var name = '小红'
var object = {
    name: '李白',
	function foo () {
	  console.log(this.name) //李白
	}
}
object.foo() //object直接调用foo(),this指向object

3.指向new 实例:

var name = '小红' 
function foo () { 
    this.name = '小白' 
    console.log(this.name) //小白 
} 
var fn = new foo() //this指向foo()的实例fn

this指向问题还是比较好理解的 总结下来就是一句话: 谁调用的函数,this就是谁

下面说一下call()函数,call()跟我们正常思维模式不太一样,脑回路回转下

Call()指向:

简单一句话: B.call(A) <==>A调用B函数,可以解释为B的this指向A。

代码示例:

function _add() {  
    console.log(this.test);  
}  
function _sub() {  
    this.test = 222;
    console.log(this.test);  
}  
_add.call(_sub); //输出undefine。这时,_add的this指向_sub,
_sub里的this指向是window,所以_sub本身没有test这个属性

_add.call(new _sub())//输出222。这时,_add的this指向_sub,
_sub里的this指向是_sub实例,可以获取到_sub的test属性,所以输出222

/******************************************************/
function _add() {  
    this.test = 444
    console.log(this.test);  
}  
function _sub() {  
    this.test = 222;
    console.log(this.test);  
}  
_add.call(_sub); //输出444。这时,_sub里的this指向是window,
所以_sub里没有test这个属性,但是_add的this指向_sub,并为_sub创建
了test属性,所以可以获取到test的值为444

如果你觉得上面说的都不是很好理解,还有方便记忆的方法

猫吃鱼,狗吃肉,奥特曼打小怪兽。
有天狗想吃鱼了
猫.吃鱼.call(狗,鱼) // 狗调用的吃鱼的函数,所以this是狗
狗就吃到鱼了
猫成精了,想打怪兽
奥特曼.打小怪兽.call(猫,小怪兽) // 猫调用了打怪兽的函数,所以this是猫

再通俗一点就是

马云会赚钱
我使用call()函数借用了马云的赚钱函数,
所以我也会赚钱了
马云.赚钱.call(我)
此时this指向我
因为是我调用的赚钱函数
转载自:https://juejin.cn/post/7213598216884224060
评论
请登录