2014-04-20 70 views
2

我已經been watching this video其中達米安說,克羅克福德把它稱爲:「超級構造模式」Javascript的超級構造函數 - 澄清?

代碼示例:(從視頻)

var signalR; 

signalR = function (url){ 
return new signalR.prototype.init(url); 
} 

signalR.prototype={ 
init:function(url) 
{ 
    this.url=url; 
} 
} 

signalR.prototype.init.prototype = signalR.prototype; 

現在,我GOOGLE了約克羅克福德和超級構造所有我能找到的是Object.create實現:

我的理解很清楚:(也是它的陷阱)

function create(o) 
{ 
function f(){}; 
f.prototype=o; 
return new f(); 
} 

但我仍沒有看到它是如何涉及:

問:

  • 究竟是什麼(視頻) - 他嘗試通過使用此模式來解決? (也是小代碼示例將非常感謝)。
+1

此模式啓用的唯一方法是您可以不帶'new'調用'signalR'。另請參閱https://stackoverflow.com/questions/15591434/which-form-of-initialization-is-better – Bergi

+0

@Bergi我相信有一點超出了這個範圍:例如 - 他實例化init方法。所以init是ctor函數.....你確定這是唯一的東西嗎?如果你把它轉換成一個答案,這將是非常感激的(ps鏈接有點真實,但不是100%,因爲在這裏,正如我所說的,他正在處理init作爲ctor函數) –

+0

是的,他使用'init '作爲構造函數,這是一個可怕的模式。 – Bergi

回答

3

讓我們來看看在正常類構造函數和原型

//------------------- 
//---- Class signalr 
//------------------- 

//-- constructor 
var signalr=function() {} 

//--prototype 
signalr.prototype.init=function (url) 
    { 
    this.url=url; 
    } 

signalr.prototype.test=function() {alert ("test");} 

//------------------- 
//---- Class signalr -- END 
//------------------- 

所以產生這個類,我們必須寫出以下的新實例。

var con=new signalr(); //--- con would inherit two methods init and test 
con.init ("yoururl"); 

讓我們看看克羅克福德

//------------------- 
//---- Class signalr - Crockford 
//------------------- 

//-- signalr is here not the constructor, it's a normal function with a return value and setted prototype, the constructor becomes init which is defined in the signalr prototype 
var signalr=function (url) 
    { 
    return new signalr.prototype.init (url); 
    } 

//--prototype 
//----------- 

    //-- constructor 
signalr.prototype.init=function (url) 
    { 
    this.url=url; 
    } 

signalr.prototype.test=function() {alert ("test");} 
signalr.prototype.init.prototype=signalr.prototype  //- with this line, the prototype of the init method which is the constructor of our instances is linked to the prototype signalR so all instances would inherit the properties and methods defined in the signalR prototype 

//------------------- 
//---- Class signalr -- END 
//------------------- 

所以產生這個類,我們可以很快寫出下面來達到同樣像上面的一個新實例。

var con=signalr ("yourURL");    //--- con inherits all the methods and properties of signalr.prototype with one line 

似乎crockford懶惰地寫行,我在考慮實際的例子。但我認爲整個事情並不令人興奮

+0

我不明白這會得到什麼。爲什麼不在真正的構造函數中調用'this.init()'? – janfoeh

+1

比你還要寫var con = new signalr(「yourURL」);)))正如我所說,我認爲他是寫作行很懶。但多數民衆贊成我的意見也許有隱藏的東西,但我不這麼認爲 –

+0

@ ThorstenArtner'Austria'我不知道他爲什麼提到crockford。我沒有發現他的一篇文章談論這種模式。你有鏈接嗎? –