SlySherZ
SlySherZ

Reputation: 1661

Accessing class members from private function

Suppose I have a class, with some methods that I need to access from private functions within that class. Like so:

var A = function( )
{
    this.a = 0;

    var f = function( ){   // Private function
        this.a;   // Undefined
    };

    f( );
};

What would be the better way to do this? I tried to pass this to the function, but it's not practical if I must do it for many functions.

var A = function( )
{
    this.a = 0;

    var f = function( self ){
        self.a;
    };

    f( this );
};

Is there a better way to do this? Or is the design fundamentally flawed and I should consider other alternatives? Thanks!

Upvotes: 0

Views: 40

Answers (2)

nempnett
nempnett

Reputation: 225

To avoid 'this' confusion a common pattern I've seen is as follows:

var A = function( ) {
    var self = this;
    self.a = 0;

    var f = function( ){   // Private function
        self.a;   // Defined
    };

    f( );
};

Upvotes: 1

Madara's Ghost
Madara's Ghost

Reputation: 174957

Why yes, with ES6, we get arrow functions, with automatic this binding!

var A = function() {
    this.a = 0;

    var f = () => {   // Private function
        console.log(this.a);   // Woohoo!
    };

    // If only one statement, can be shortened to
    // var f = () => console.log(this.a);

    f();
};

For the less fortunate: .bind() also exists:

var A = function() {
    this.a = 0;

    var f = function() {   // Private function
        console.log(this.a);   // Woohoo!
    }.bind(this); // this inside the function is bound to the passed this.

    // If only one statement, can be shortened to
    // var f = () => console.log(this.a);

    f();
};

Upvotes: 1

Related Questions