gpt4 book ai didi

javascript - 什么方法最适合在 JavaScript 中实例化其他函数的函数?

转载 作者:行者123 更新时间:2023-12-02 19:36:45 24 4
gpt4 key购买 nike

我一直在使用这种方法:

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
};
}

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

最佳答案

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,你可以使用原型(prototype):

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 () { .. } .

It is never a good idea to put new directly in front of function. For example, new function provides no advantage in constructing new objects. By using new to invoke the function, the object holds onto a worthless prototype object. That wastes memory with no offsetting advantage.

关于javascript - 什么方法最适合在 JavaScript 中实例化其他函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10840316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com