gpt4 book ai didi

javascript - JavaScript 闭包内的命名空间对象初始化

转载 作者:行者123 更新时间:2023-12-03 10:22:56 25 4
gpt4 key购买 nike

我从 http://frugalcoder.us/post/2010/02/11/js-classes.aspx 中获取了此片段:

if (typeof My == 'undefined')
My = {};
if (typeof My.Namespace == 'undefined')
My.Namespace = {};
//begin private closure
(function(){

//this is a private static member that is only available in this closure
var instances = 0;

//this is a private static method that can be used internally
function _incrementInstances() {
instances++;
}

//Define SomeClass (js uses functions as class constructors, utilized with the "new" keyword)
this.SomeClass = function(options) {
//if the function is called directly, return an instance of SomeClass
if (!(this instanceof SomeClass))
return new SomeClass(options);

//call static method
_doSomething();

//handle the options initialization here
}

//create a public static method for SomeClass
this.SomeClass.getInstanceCount = function() {
return instances; //returns the private static member value
}

//create an instance method for SomeClass
this.SomeClass.prototype.doSomething = function() {
/*Do Something Here*/
}

//end private closure then run the closure, localized to My.Namespace
}).call(My.Namespace);

然后,在 document.ready 回调中,两者:

$(function () {
My.Namespace.SomeClass({});
});

和:

$(function () {
new My.Namespace.SomeClass({});
});

报错如下:

Uncaught ReferenceError :SomeClass 未定义

我错过了什么?我想也许是因为教程太旧了(2010 年)?

提前致谢!

最佳答案

该代码根本不正确。但它可以修复:

this.SomeClass = function SomeClass(options) { // <--- Name the function
//if the function is called directly, return an instance of SomeClass
if (!(this instanceof SomeClass))
return new SomeClass(options);

//call static method
_doSomething();

//handle the options initialization here
}

通过为函数指定这样的名称,符号“SomeClass”将在函数内部用作(对其自身的)引用。

请注意,_doSomething 也未定义,并且构造函数实际上并不调用该计算实例的函数。

关于javascript - JavaScript 闭包内的命名空间对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29544147/

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