当前损坏的代码:http://jsfiddle.net/9F52n/2/
我正在尝试做什么:学习如何定义一个类似于类的对象/函数,并且能够定义子类,包括静态和可实例化的(在下面的示例中为singleton)。
目前,我的代码不能很好地运作。但是,如果删除了静态类的可实例化类沙,那么你会看到我已经完成了类创建的基础知识。
所以,我想我的问题是:用我定义TBR的方式定义嵌套clases(singleton或其他)的正确/最具语义的方法是什么? (function(){...})(window)
var TBR = (function() {
// define local copy of taco bell run
var TBR = function() {
return new TBR.fn.init();
},
message = "hello world!";
TBR.fn = TBR.prototype = {
constructor: TBR,
init: function() {
console.log("From TBR Constructor: " + message);
}
}
var InstantiatableClass = function() {
return new TBR.InstantiatableClass, fn.init();
}
InstantiatableClass.fn =InstantiatableClass.prototype = {
constructor: TBR.InstantiatableClass,
init: function() {
console.log("from InstantiatableClass: " + message);
}
}
this.staticClass = function() {
var subMessage = "little world";
init = function() {
console.log("from staticClass: " + subMessage);
}
}
// expose TBR to the window object
window.TBR = TBR;
})(window);
答案 0 :(得分:0)
var InstantiatableClass = function() {
return new TBR.InstantiatableClass, fn.init();
}
InstantiatableClass.fn =InstantiatableClass.prototype ...
这不起作用。您的InstantiatableClass
局部变量返回对象,原型将不会应用于它们。此外,TBR.InstantiatableClass
无处定义。如果这是你想要的,你需要使用
function InstantiatableClass() {
// common constructor things
}
TBR.InstantiatableClass = InstantiatableClass; // assign a "static" property
另外,你不应该[需要]覆盖原型。当然,唯一的区别是constructor
现在是可枚举的(只要它没有被遗忘),但以下会更清晰:
InstantiatableClass.fn = InstantiatableClass.prototype; // shortcut
InstantiatableClass.fn.init = function() { … };
哦,你想要像jQuery一样的东西。 Imho你不应该把构造函数(init
)作为原型的属性 - 这很奇怪,我看不出这样做的理由。我建议这段代码:
window.TBR = (function() {
function TbrConstructor() {
…
}
function InstantiableConstructor() {
…
}
// Now, the creator functions:
function TBR() { return new TbrConstructor; }
function Instantiable() { return new InstantiableConstructor; }
// Now, overwrite the "prototype" properties - this is needed for
// (new TbrConstructor) instanceof TBR === true
// and also create those fn shortcuts
TBR.fn = TBR.prototype = TbrConstructor.prototype;
Instantiable.fn = Instantiable.prototype = InstantiableConstructor.prototype;
// we might overwrite the "constructor" properties like
TBR.fn.constructor = TBR;
// but I don't see much sense in that - they also have no semantic value
// At last, make Instantiable a property on the TBR function object:
TBR.Instantiable = Instantiable;
// and then only
return TBR;
})();
// Usage
TBR(); // returns a TbrConstructor instance
TBR.Instantiable(); // returns a InstantiableConstructor instance