2012-07-05 20 views
3

如果我有僞代碼,如:調用一次函數的多種方法

function user(a,b) 
    { 
    if(! (this instanceof user)) return new user(a,b); 
    this.a = a; 
    this.b = b; 
    this.showName = function() { 
     alert(this.a + " " + this.b); 
    }; 

    this.changeName = function(a,b) { 
     this.a = a; 
     this.b = b; 
    }; 
    } 

我可以把它想:

user("John", "Smith").showName() // output : John Smith 

我想是這樣的:

user("John", "Smith").changeName("Adam", "Smith").showName(); 

回答

7

以每種方法返回對象。這被稱爲「鏈接」。

function user(a,b) 
    { 
    if(! (this instanceof user)) return new user(a,b); 
    this.a = a; 
    this.b = b; 
    this.showName = function() { 
     alert(this.a + " " + this.b); 

     return this; // <--- returning this 
    }; 

    this.changeName = function(a,b) { 
     this.a = a; 
     this.b = b; 

     return this; // <--- returning this 
    }; 
} 

DEMO:http://jsbin.com/oromed/

+0

非常感謝,它的工作原理。我不知道這個 – John 2012-07-05 12:54:57

+1

爲了將來的參考,這種模式被稱爲「鏈接」。 – 2012-07-05 12:59:27

+0

請了解['範圍](https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/)是 – Esailija 2012-07-05 13:02:22