如何向函数添加方法?

时间:2011-08-08 22:36:40

标签: javascript

具体来说,我如何编写允许链接的原型,如下所示:

$('myDiv').html('Hello World').fadeIn('slow');

4 个答案:

答案 0 :(得分:5)

您描述的技术称为fluent interface,它涉及从所有可链接函数返回相同类型的对象。该对象的原型包含函数定义。

链接文章包含各种语言的示例代码,包括javascript。

答案 1 :(得分:1)

只需从函数中返回适当的内容即可。基本的经验法则是采用任何方法,这些方法通常会返回任何内容并使其返回this

function Constructor(){};

Constructor.prototype = {
    foo: function(){
        console.log('foo');
        return this;
    },
    bar: function(x){
        console.log('bar', x);
        return this;
    }
}

var obj = new Constructor();
obj.foo().bar(17).bar(42).foo();

答案 2 :(得分:1)

在该特定情况下,每个方法都返回this。所以:

// ... this has to be the most impractical class I've ever written, but it is a
// great illustration of the point.
var returner = new function() {
    this.returnThis = function(){
        console.log("returning");
        return this
     }
 }
 var ret2 = returner.returnThis().returnThis().
           returnThis().returnThis() // logs "returning" four times.

 console.log( ret2 == returner ) // true

答案 3 :(得分:1)

链接示例:

var avatar = function() {

    this.turnLeft = function {
       // some logic here
       return this;
    }

    this.turnRight = function {
       // some logic here
       return this;
    }

    this.pickUpItem = function {
       // some logic here
       return this;
    }

};


var frodo = new avatar();
frodo.turnLeft().turnRight().pickUpItem();