Kirk Strobeck
Kirk Strobeck

Reputation: 18559

Object Oriented JavaScript shared method variables

Why doesn't this work?

function thing() {

    var bigvar;

    function method1() {
        bigvar = 1;
    }

    function method2() {
        alert(bigvar);
    }

    this.method1 = method1;
}

var a = new thing();
a.method1();
a.method2();
​

I want method2 to work, but it doesn't .. is there a way to make this work?

Upvotes: 0

Views: 63

Answers (3)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66921

Why not do this?

function thing() {

    var bigvar;

    this.method1 = function () {
        bigvar = 1;
    }

    this.method2 = function () {
        alert(bigvar);
    }

}

var a = new thing();
a.method1();
a.method2();​

Upvotes: 0

Polyov
Polyov

Reputation: 2311

Why do you have this.method1 = method1 but not this.method2 = method2? Try that.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You did not make method2 public like method1 is.

this.method1 = method1;
this.method2 = method2;  //<-- missing this

Upvotes: 3

Related Questions