请问js中call与apply区别?
网友回复
在回答你的问题之前,我们想理解一下js中this关键字
在面向对象语言中 this 表示当前对象的一个引用。
但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。
在方法中,this 表示该方法所属的对象;
如果单独使用,this 表示全局对象;
在函数中,this 表示全局对象;
在函数中,在严格模式下,this 是未定义的(undefined);
在事件中,this 表示接收事件的元素。
那么call() 和 apply() 方法可以将 this 引用到任何对象。
apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象。
先看看call的写法:<script type="text/javascript">
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName: "John",
lastName: "Doe",
}
/*console.log(person1.fullName.apply(person2)); // 返回 "John Doe"*/
console.log(person1.fullName.call(person2)); // 返回 "John Doe"
</script>
使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法。
在看看call()的另外一种用法:<script type="text/javascript">
function person1(name, age) {
this.name = name;
this.age = age;
}
function person2(name, age, grade) {
person1.call(this, name, age);
this.grade = grade;
}
var person = new person2("xiaoming", 20, "dasan");
console.log(person.name+person.age+person.grade); ...点击查看剩余70%
有没有免费让ai自动帮你接管操作电脑的mcp服务?
mcp为啥用Streamable HTTP 替代 HTTP + SSE?
scratchjr有没有开源的前端html网页版本源代码?
多模态大模型能否根据ui交互视频来来模仿写出前端交互动画效果ui代码?
如何用阿里云oss+函数计算fc+事件总线EventBridge+消息队列+数据库+redis缓存打造一个高并发弹性系统?
阿里云函数计算 FC如何在海外节点搭建一个代理网络?
ai studio中gemini build的代码如何发布到github pages等免费网页托管上 ?
如何在cursor、qoder、trae中使用Claude Skills功能?
有没有不用u盘就能重装系统的开源工具?
python如何固定摄像头实时计算停车场停车位剩余数量?


