当前损坏的代码:http://jsfiddle.net/9F52n/2/
我想要做的是:学习如何定义一个像类一样行为的对象/函数,并且能够定义静态和实例化的子类(在下面的例子中是单例)。
目前,我下面的代码并不能很好地工作。但是,如果删除了可实例化的类和静态类,您将看到我已经掌握了类创建的基础知识。
所以,我想我的问题是:用我定义的TBR的方式来定义嵌套类(单例或其他)最合适/最具语义的方式是什么?(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);发布于 2012-08-06 22:59:57
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那样工作的东西。我不应该让构造函数(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 instancehttps://stackoverflow.com/questions/11830651
复制相似问题