Javascript方法链
我一直在试图找到一种方法,以类似于jQuery的方式将这些方法链接在一起。以下是我的意思的一个例子:Javascript方法链,javascript,jquery,class,method-chaining,Javascript,Jquery,Class,Method Chaining,我一直在试图找到一种方法,以类似于jQuery的方式将这些方法链接在一起。以下是我的意思的一个例子: (function() { window.foo = function foo( id ) { if( window == this ) return new foo( document.getElementById( id ) ); this.alert = function() { alert( obj
(function() {
window.foo = function foo( id ) {
if( window == this )
return new foo( document.getElementById( id ) );
this.alert = function() {
alert( object.value );
}
}
}());
foo('input').alert();
如您所见,我希望将传递到类中的对象用作警报函数的一部分,但我不希望通过this.object=id
将其存储在类中,然后执行警报(this.object.value)代码>
有什么优雅的方法可以做到这一点呢?只通过从许多方法返回相同的jQuery对象来链接jQuery。您的方法并不总是返回值,因此它不会可靠地链接。如果您总是让它返回相同类型的值,那么链接可能就开始有意义了
window.foo = function foo( id ) {
if( window === this )
return new foo( document.getElementById( id ) );
this.alert = function() {
if (this.value) alert( this.value );
}
return this;
}
foo('input').alert();
您不需要在对象中存储引用,因为您已经将其作为id
存储
this.alert = function() {
alert(id.value);
return this;
}
也许你应该读一下:)