面向对象的 JavaScript 共享方法变量

Object Oriented JavaScript shared method variables

本文关键字:变量 方法 共享 JavaScript 面向对象的      更新时间:2023-09-26

为什么这不起作用?

function thing() {
    var bigvar;
    function method1() {
        bigvar = 1;
    }
    function method2() {
        alert(bigvar);
    }
    this.method1 = method1;
}
var a = new thing();
a.method1();
a.method2();
​

我希望方法2工作,但它没有..有办法使它工作吗?

你没有像method1那样公开method2

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

为什么你有this.method1 = method1而没有this.method2 = method2?试试看。

为什么不这样做呢?

function thing() {
    var bigvar;
    this.method1 = function () {
        bigvar = 1;
    }
    this.method2 = function () {
        alert(bigvar);
    }
}
var a = new thing();
a.method1();
a.method2();​