0

我一直在使用这种方法:

var __foo = new function(){
 var _id = null;
 function GetId(){
  return _id;
 }
 function SetId(id){
  _id = id;
 }
 return{
  GetId : GetId,
  SetId : SetId,
 };
}

var __fooFactory = function(){
 var _foos = [];
 var _autoIncFooId = 0;

 function CreateFoo(){
  var newFoo = new __foo();
  newFoo.SetId(_autoIncFooId++);
  _foos.push(newFoo);
 }

 return{
  CreateFoo : CreateFoo
 };
}

我应该更多地使用原型而不是这个实现吗?这种方法有替代方法吗?(我对 jQuery 的想法持开放态度,但如果是这样,请将它们保持在 1.4.4 或注意版本合规性)

4

1 回答 1

2

Foo 构造函数:

function Foo(i) {
    var id = i; // private

    this.getId = function () {
        return id;
    };

    this.setId = function (i) {
        id = i;
    };
}

工厂构造函数:

function FooFactory() {
    var i = 0,
        foos = [];

    this.createFoo = function () {
        var foo = new Foo(i++);
        foos.push(foo);
        return foo;
    };
}

用法:

var fooFactory0 = new FooFactory(),
    foo00 = fooFactory0.createFoo(), // getId() -> 0
    foo01 = fooFactory0.createFoo(); // getId() -> 1

var fooFactory1 = new FooFactory(),
    foo10 = fooFactory1.createFoo(), // getId() -> 0
    foo11 = fooFactory1.createFoo(); // getId() -> 1

如果你想要 public id,你可以使用原型:

function Foo(i) {
    this.id = i; // public
}

Foo.prototype.getId = function () {
    return this.id;
};

Foo.prototype.setId = function (i) {
    this.id = i;
};

Crockford 对var Foo = new function () { .. }的看法。

new直接放在前面绝对不是一个好主意function。例如,new function在构造新对象时没有优势。通过使用new来调用函数,对象持有一个毫无价值的原型对象。这会浪费内存而没有抵消优势。

于 2012-05-31T22:25:58.377 回答