js call()、apply()、bind()的区别和使用
js call()、apply()、bind()的区别和使用
写在前面:
-
call和apply可以用来重新定义函数的执行环境,也就是this的指向; call 和 apply 都是为了改变某个函数运行时的
context 即上下文而存在的 换句话说,就是为了改变函数体内部 this 的指向。因为 JavaScript
的函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。 -
call() 就是用来让括号里的对象 来集成括号外的函数的属性!可以称之为继承!
call:
目的: 改变函数运行时的上下文(context),即this指向
说人话: 就是“劫持”(继承)别人的方法
例子:person.fullName.call(person1)
即 对象person1继承了person的fullName方法
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
person.fullName.call(person1); // 将返回 "Bill Gates"
另外: call()也可以传递其他参数:call(thisObj, arg1, arg2, arg3, arg4);
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");
打印结果:
apply: 同 call
目的: 改变函数运行时的上下文(context),即this指向
例子:person.fullName.apply(person1)
即 对象person1继承了person的fullName方法
和call的区别: 传递其他参数时需要使用[]
传递其他参数:apply(thisObj, [arg1, arg2, arg3, arg4]);
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.apply(person1, ["Seattle", "USA"]);
打印结果:
bind: 同call、apply
目的: 改变函数运行时的上下文(context),即this指向
和call、apply的区别: 使用的返回值是个方法,也就是bind(thisObj)()实现
传递其他参数:bind(thisObj, arg1, arg2, arg3, arg4)();
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.bind(person1, "Seattle", "USA")();
打印结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了