我尝试创建一些基于 jQuery 风格的类,如下面的代码。
myClass = window.myClass = function(x, y)
{
return new myClass.fn.init(x, y);
};
myClass.fn = myClass.prototype =
{
init: function(x, y)
{
// logic for creating new myClass object.
}
};
我不明白为什么 jQuery 使用 new 关键字来创建它的类,因为根据我的实验,JavaScript 总是创建 myClass.init 对象而不是 myClass 对象。但是,我尝试删除 myClass 构造函数中的 new 关键字。但它仍然没有改变。你能解释一下为什么 jQuery 可以做到这一点,但我不能,或者给我一些在 init 函数中使用的代码吗?
顺便说一句,我可以使用以下代码而不是 jQuery 样式代码来创建相同的对象。我的代码和 jQuery 代码有什么不同?使用 jQuery 风格有什么好处吗?
myClass = window.myClass = function(x, y)
{
this.init(x, y);
};
myClass.fn = myClass.prototype =
{
init: function(x, y)
{
this.x = x;
this.y = y;
}
};
PS。我喜欢编写将初始逻辑分离为函数的代码,因为使用我的代码的其他人(如我的以下代码)很容易覆盖此函数。
// override init function of myClass
myClass.fn._old_init = myClass.fn.init;
myClass.fn.init = function()
{
// logic for doing something before init
this._old_init();
// logic for doing something after init
};
谢谢,
最佳答案
这种方法应该可以完美工作。您可能会忽略的一件事是,使用这种技术,您不会创建 myClass
的实例;您将创建 myClass.prototype.init
的实例。
因此,myClass.prototype
中定义的任何方法都无法用于该实例。您需要确保 init
的原型(prototype)指向 myClass
的原型(prototype):
myClass.fn.init.prototype = myClass.fn;
<小时/>
FWIW,我认为这种方法没有任何真正的好处。这有什么问题吗? -
function myClass(x,y) {
if ( !(this instanceof myClass) ) {
return new myClass(x,y);
}
// Prepare instance
}
myClass.prototype = { /* Methods */ };
// It can still be overwritten:
var oldMyClass = myClass;
function myClass(x,y) {
// Hack some stuff here...
return new oldMyClass(x,y);
}
关于javascript - 为什么 jQuery 使用 "new jQuery.fn.init()"来创建 jQuery 对象,但我不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1856890/