开发者

How do I add a method to a function?

Specifically, how can I write prototypes that allow chaining, such as the following:

$('myDiv').html('Hello World').fade开发者_StackOverflow中文版In('slow');


The technique you're describing is called fluent interface, and it involves returning the same kind of object from all chainable functions. That object's prototype contains the function definitions.

The linked article includes example code in various languages, including javascript.


Just return the appropriate stuff from the functions. The basic rule of thumb is take any method that would normaly return nothing and make it return this instead.

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();


In that particular situation, each method returns this. So:

// ... 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


Chaining example:

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜