函数调用方式java_js函数的四种调用方式以及对应的this指向

一、函数调用,此时this是全局的也就是window

1 var c=function(){

2 alert(this==window) 3 } 4 c()//true

二、方法调用

99b88b317ac7076c5750aa9201f56eac.png

var myObj={

value:2,

inc:function(num){

alert(this.value+num); } } myobject.inc(1); //结果3,因为this指向myObj

c601a0d7e70f7836a9ebe5757cbdaa04.png

注意:内部匿名函数不属于当前对象的函数,因此this指向了全局对象window

7a67e5d2bd62078163ced3c56e20ab5c.png

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];

41554523c61bc77a3c41ec9d4ed4e28d.png

解决方法:

32156ec442a75a91b8854826c6f78fee.png

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}]

0ce0450b0e9662e5ab43bdcbbe17af86.png

三、用new关键字来新建一个函数对象的调用,this指向被绑定到构造函数的实例上

62b332f69abdc20a84009c756c4e28c4.png

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

0f5711bd0d7eb2dbef869cf3744b1018.png

四、apply/call调用

db1ace8afa23d9e10e07fccbf4a59802.png

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

6dbad1ff98772ff1568c0b7e86a71607.png

通过call和apply可以重新定义函数的执行环境,即this的指向,这对于一些应用当中是十分常用的。

https://www.cnblogs.com/qlqwjy/category/1035591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值