Nat
Nat

Reputation: 908

Accessing outer scope from inner scope

I have a type that looks a little something like this:

var x = function(){
    this.y = function(){

    }

    this.z = function(){
        ...
        this.A = function(){
            CALLING POINT
        }
    }
}

From calling point, I'm attempting to call function this.y. I don't need to pass any parameters, but when I set some stuff from this.A, I need to call this.y.

Is this possible? I'm OK with passing extra parameters to functions to make it possible.

Upvotes: 6

Views: 9626

Answers (4)

Michael Biermann
Michael Biermann

Reputation: 3133

Instead of function() you can try modern JavaScript or Typescript ()=>. I also like .bind(this).

Upvotes: 1

isvforall
isvforall

Reputation: 8926

Is this possible?

Yes, you can assign this reference to another variable and then call function y on it

this.z = function() {
    var self = this;
    this.A = function() {
        self.y();
    }
}

Upvotes: 11

Nina Scholz
Nina Scholz

Reputation: 386868

Version with bind, basically this adds a new method a to the object.

var X = function () {
    this.y = function () {
        document.write('y<br>');
    }

    this.z = function () {
        document.write('z<br>');
        this.a = function () {
            document.write('a<br>');
            this.y();
        }
    }.bind(this);
};

var x = new X;
//x.a(); // does not exist
x.z();   // z
x.a();   // a y

Working example with saved inner this.

var X = function () {
    var that = this; // <--

    this.y = function () {
        document.write('y<br>');
    }

    this.Z = function () {
        document.write('Z<br>');
        this.a = function () {
            document.write('a<br>');
            that.y();
        }
    }
}

var x = new X,
    z = new x.Z; // Z

z.a(); // a y

Upvotes: 7

Obinna Nwakwue
Obinna Nwakwue

Reputation: 209

You cannot because this.y() is not within the scope that this.A() is in. You can if you set this.y() to a global function y:

var y = function() {};
var x = function() {
    this.y = y;
    this.z = function() {
       ...
       this.A = function() {
           this.y(); // will be successful in executing because this.y is set to the y function.
       };
    }
};

Upvotes: -1

Related Questions