【发布时间】:2009-12-06 22:40:11
【问题描述】:
我尝试创建一些基于 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
};
谢谢,
【问题讨论】:
标签: javascript jquery oop