2011-08-08 111 views

回答

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

這正是我想要的。謝謝!! – 0x499602D2

5

您所描述的技術被稱爲fluent interface,它涉及所有可鏈接的功能返回相同類型的對象。該對象的原型包含函數定義。

鏈接的文章包含各種語言的示例代碼,包括javascript。

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