JavaScript中的方法调用详细介绍

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

  

复制代码 代码如下:

  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中还可以通过使用中括号操作符来进行方法调用:

  

复制代码 代码如下:

  //other ways to invoke method

  sample["act"](7);

  console.log(sample.x);//49

  对于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值保存到一个变量中:

  

复制代码 代码如下:

  //pass "this" to nested function

  var sample4 = {

  act4:function(){

  var self = this;

  inner();

  function inner(){

  console.log(self);//Object {act4=function()}

  }

  }

  }

  sample4.act4();