Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript方法链_Javascript_Jquery_Class_Method Chaining - Fatal编程技术网

Javascript方法链

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

我一直在试图找到一种方法,以类似于jQuery的方式将这些方法链接在一起。以下是我的意思的一个例子:

(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;
}
也许你应该读一下:)