0

Am just getting the ropes of JS Fundamentals, bear with me.

Following is the code :

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
};

}

Both external function and inner functions variable names are same i.e., x & y. How do i access external function FuncWithMathOps variables from inner functions SUM & MUL ?

3

1 Answer 1

3

You can create a variable self which persist the reference to this, which can be used later.

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

You can also use .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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.