0

Here is an example can anybody tell me how to do this

var calculation = function(){
    this.Add = function(){
    }
    this.Subtract(){
        var add = function(){
        //want to access Add function here
        }
    }
}
0

2 Answers 2

3

You can simply use a variable to refer to this and you can use that variable latter.

var calculation = function() {
  var _this = this;

  this.Add = function() {
    alert('In Add function');
  }

  this.Subtract = function() {
    var add = function() {
      //want to access Add function here
      _this.Add();
    }
    
    add();
  }
};

var cal = new calculation()
cal.Subtract()

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

3 Comments

@BhojendraSah, this.Subtract = function() { and OPs this.Subtract(){
It would be nice to stick to convention with captialisation of constructor and method names.
Personally I only would use var _this = this; when using this in the function. Otherwise I'll use the bind method. See my answer.
-1

Try this:

vvar calculation = function(){
    this.Add = function(){
        alert("test");
    }
    this.Subtract = function(){
        this.Add();
    }.bind(this)
}

var sum = new calculation();
sum.Subtract();

http://jsfiddle.net/f6rp9mpL/

3 Comments

That code is littered with syntax errors, and bind is core JavaScript, it doesn't come from jQuery.
Sorry, did the coding a littlebit too quick. Edited my answer.

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.