如何从JavaScript中的内部函数访问外部函数变量?

时间:2017-02-15 12:53:15

标签: javascript node.js

刚刚获得JS Fundamentals的绳索,请耐心等待。

以下是代码:

function FuncWithMathOps(x){
var x=x;

console.log("Value of x : "+x);

var SUM = function(x){
    var x=x;

    console.log("Value of x : "+x);
    console.log("Value of this.x : "+this.x);
}

var MUL = function(x){
    var x=x;

    console.log("Value of x : "+x);
    console.log("Value of this.x : "+this.x);
}

return {
    SUM:SUM,
    MUL:MUL
};

}

外部函数和内部函数变量名都相同,即x& y。如何从内部函数FuncWithMathOps&中访问外部函数SUM变量? MUL

1 个答案:

答案 0 :(得分:3)

您可以创建一个变量 self ,它会保留对this的引用,以后可以使用。



function FuncWithMathOps(x) {
  this.x = x;
  var self = this;

  console.log("Value of x : " + x);
  var SUM = function(x) {
    console.log("Value of x : " + x);
    console.log("Value of this.x : " + self.x);
    return x + self.x;
  }

  return {
    SUM: SUM
  };
}

var fn = new FuncWithMathOps(10);
console.log(fn.SUM(5))




您也可以使用.bind()



function FuncWithMathOps(x) {
  this.x = x;
  console.log("Value of x : " + x);
  var SUM = function(x) {
    console.log("Value of x : " + x);
    console.log("Value of this.x : " + this.x);
    return x + this.x;
  }

  return {
    SUM: SUM.bind(this)
  };
}

var fn = new FuncWithMathOps(10);
console.log(fn.SUM(5))