js函数的四种调用方式以及对应的this指向
一、函数调用,此时this是全局的也就是window
1 var c=function(){
2 alert(this==window)
3 }
4 c()//true
二、方法调用
var myObj={
value:2,
inc:function(num){
alert(this.value+num);
}
}
myobject.inc(1); //结果3,因为this指向myObj
注意:内部匿名函数不属于当前对象的函数,因此this指向了全局对象window
var myObj={
name:'myObject',
value:0,
increment:function(num){
this.value += typeof(num) ==='number'? num:0;
},
toString:function(){
return '[object:'+this.name+'{value:'+this.value+'}]';
},
getInfo:function(){
return (function(){
return this.toString();//内部匿名函数不属于当前对象的函数,因此this指向了全局对象window
})();
}
}
alert(myObj.getInfo());//[object window];
解决方法:
var myObj={
name:'myObject',
value:0,
increment:function(num) {
this.value += typeof(num) ==='number' ? num : 0;
},
toString:function() {
return '[object:'+this.name+'{value:'+this.value+'}]';
},
getInfo:function(){
var This=this;//先把当前的this指向存起来
return (function(){
return This.toString();
})();
}
}
alert(myObj.getInfo());//[Object:myObject {value:0}]
三、用new关键字来新建一个函数对象的调用,this指向被绑定到构造函数的实例上
var fn = function (status){
this.status = status;
}
fn.prototype.get_status = function(){
return this.status;
}
var test = new fn('my status');
alert(test.get_status);//my status,this指向test
四、apply/call调用
function MyObject(name){
this.name=name ||'MyObject';
this.value=0;
this.increment=function(num){
this.value += typeof(num) === 'number' ? num : 0;
};
this.toString=function(){
return '[Object:'+this.name+' {value:'+this.value+'}]';
};
this.target=this;
}
function getInfo(){
return this.toString();
}
var myObj=new MyObject();
alert(getInfo.apply(myObj));//[Object:MyObject {value:0}],this指向myObj
alert(getInfo.apply(window));//[object Window],this指向window
通过call和apply可以重新定义函数的执行环境,即this的指向,这对于一些应用当中是十分常用的。
【当你用心写完每一篇博客之后,你会发现它比你用代码实现功能更有成就感!】
分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix