JavaScript中的call()函数如何使用

本文讲解"JavaScript中的call()函数怎么使用",希望能够解决相关问题。

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指向我
因为是我调用的赚钱函数

关于 "JavaScript中的call()函数怎么使用" 就介绍到此。希望多多支持编程宝库

今天用vue3配置嵌套路由时,发现刷新页面后,页面变为空白,打开控制台发现报错:Uncaught SyntaxError: U ...