源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JavaScript中的方法调用详细介绍

  • 时间:2020-06-06 13:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JavaScript中的方法调用详细介绍
JavaScript中,如果function属于一个对象,那么通过对象来访问该function的行为称之为“方法调用”。与普通的函数调用不同的是,在进行方法调用时,function中的this指代将发生变化 — this将指代用于调用该function的对象(该对象将成为方法调用的invocation context):
[u]复制代码[/u] 代码如下:
var x = 99; var sample = {   x:1,   act:function(a){     this.x = a*a;//assign value to sample's x, not global object's x.   } } sample.act(6); console.log(sample.x);//36 console.log(x);//99
与访问对象中的property一样,除了使用点号操作符,JavaScript中还可以通过使用中括号操作符来进行方法调用:
[u]复制代码[/u] 代码如下:
//other ways to invoke method sample["act"](7); console.log(sample.x);//49
对于JavaScript中的function,一个比较有趣的行为是可以在function中嵌入function(闭包)。在进行方法调用时,如果方法function中有嵌入的function,那么这个嵌入的function中的代码可以访问到外部的变量值:
[u]复制代码[/u] 代码如下:
//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指代的并不是调用方法的对象,而是全局对象:
[u]复制代码[/u] 代码如下:
//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值保存到一个变量中:
[u]复制代码[/u] 代码如下:
//pass "this" to nested function var sample4 = {   act4:function(){     var self = this;     inner();     function inner(){         console.log(self);//Object {act4=function()}     }   } } sample4.act4();
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部