1

我正在尝试Foo在 JavaScript 中创建一个类似于对象的类(称为Foo. 通过多个实例,我的意思是,每个实例都将保持单独的内部状态。这就是我实现它的方式。

var Foo = function() {
    function init(a) {
        this.a = a
    }

    function state() {
        return this.a
    }

    function getFoo() {
        return {
            init: init,
            state: state
        }
    }

    return {
        getFoo: getFoo
    }
}()

var a = Foo.getFoo()
var b = Foo.getFoo()
a.init(10)
b.init(20)
alert(a.state() + ', ' + b.state())

如您所见,它Foo.getFoo()似乎模拟了 Java 中通常使用的工厂模式。内部状态是变量this.a。我认为我的尝试是成功的,因为a.state()b.state()显示了两种不同的内部状态。然而,这纯粹是我的尝试,不知道这些东西是如何在行业中实现的。

现在,我的问题可能看起来像是代码审查请求,并且有被关闭的风险,所以我会尽量让我的问题尽可能客观。

  1. 如何实现相同的代码,以便new使用运算符来创建具有this.a内部状态的类的新实例?
  2. 我的工厂模式代码在业界是怎么写的?
4

1 回答 1

3
var Foo = function (a) {
    this.a = a;
};
Foo.prototype.state = function () {
    return this.a;
};

var a = new Foo(10);
a.state(); // 10

Bun,您还可以从构造函数本身声明状态方法,例如:

var Foo = function (a) {
    this.a = a;
    this.state = function () {
        return this.a;
    };
};

更新:工厂模式。

我通常将它用于我的工厂:

var Foo = function (a) {
    this.a = a;
};
Foo.prototype.state = function () {
    return this.a;
};

var FooFactory = function () {};
FooFactory.prototype.create = function (a) {
    return new Foo(a);
};

var factory = new FooFactory();
var a = factory.create(20);
a instanceOf Foo; // true
a.state(); // 20
于 2013-08-22T06:02:57.160 回答