我的最终目标是能够做这样的事情:
MyVar(parameter).functionToPerform();
够傻的,即使在阅读了变量的声明方式、查看了 jQuery 代码之后,......我仍然无法理解它。
这是我到目前为止尝试过的方法,但它失败了:
var MyClass = function(context) {
this.print = function(){
console.log("Printing");
}
this.move = function(){
console.log(context);
}
};
var test = new MyClass();
test.print(); // Works
console.log('Moving: ' + test('azerty').move() ); // Type property error
最佳答案
在我撰写本文时,Squeegy 的答案获得了最高票数:7。然而它是错误的,因为 __proto__
是非标准的并且不受 Internet Explorer(甚至版本 8)支持。然而,摆脱 __proto__
并不能让它在 IE 6 中正常工作。
这(有点简化)是 jQuery 实际执行此操作的方式 (even try it on IE 6),它还包括静态方法和方法链接的示例。关于 jQuery 如何做的所有细节,当然,您必须查看 jQuery source code自己。
var MyClass = function(context) {
// Call the constructor
return new MyClass.init(context);
};
// Static methods
MyClass.init = function(context) {
// Save the context
this.context = context;
};
MyClass.messageBox = function(str) {
alert(str);
};
// Instance methods
MyClass.init.prototype.print = function() {
return "Printing";
};
MyClass.init.prototype.move = function() {
return this.context;
};
// Method chaining example
MyClass.init.prototype.flash = function() {
document.body.style.backgroundColor = '#ffc';
setInterval(function() {
document.body.style.backgroundColor = '';
}, 5000);
return this;
};
$('#output').append('<li>print(): '+ MyClass().print() +'</li>');
$('#output').append('<li>flash().move():'+ MyClass('azerty').flash().move() +'</li>');
$('#output').append('<li>context: '+ MyClass('azerty').context +'</li>');
MyClass.messageBox('Hello, world!');
请注意,如果您需要“私有(private)”数据,则必须将实例方法放在 MyClass.init
中(在该函数中声明一个变量)作为 this.print = function () { ... };
而不是使用 MyClass.init.prototype
。
关于javascript - 创建一个类似 "$"对象的 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4556110/