微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript中的方法调用详细介绍

JavaScript中,如果function属于一个对象,那么通过对象来访问该function的行为称之为“方法调用”。与普通的函数调用不同的是,在进行方法调用时,function中的this指代将发生变化 — this将指代用于调用该function的对象(该对象将成为方法调用的invocation context):

代码如下:

与访问对象中的property一样,除了使用点号操作符,JavaScript中还可以通过使用中括号操作符来进行方法调用

代码如下:

对于JavaScript中的function,一个比较有趣的行为是可以在function中嵌入function(闭包)。在进行方法调用时,如果方法function中有嵌入的function,那么这个嵌入的function中的代码可以访问到外部的变量值:

代码如下:
nested function can access variable outside of it. var y = 88; var sample2 = { y:1, act2:function(a){ this.y = inner(); function inner(){ return a*a; } } } sample2.act2(8); console.log(sample2.y);//64 console.log(y);//88

不过,与直觉相反的是,嵌入function中的代码无法从外部继承this;也就是说,在嵌入的function中,this指代的并不是调用方法的对象,而是全局对象:

代码如下:
nested function does not inherit "this". The "this" in nested function is global object var sample3 = { act3:function(){ inner(); function inner(){ console.log(this);//window object } } } sample3.act3();

如果确实需要在嵌入function中访问到调用方法的对象,可以在外部function中将this值保存到一个变量中:

代码如下:
nested function var sample4 = { act4:function(){ var self = this; inner(); function inner(){ console.log(self);//Object {act4=function()} } } } sample4.act4();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐