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();

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...