2014-01-09 39 views
0

我有一個JavaScript函數用作構造函數。將包裝對象添加到原型對象

所使用的所有函數都被添加到函數的prototype對象中。

但是,因爲有這麼多人,我很好奇,如果我可以「組合」他們到一些包裝對象。如果我這樣做,構造函數的this實例會丟失。

function FilesManager() { 
    this._init(); 
}; 
FilesManager.prototype._init = function() { }; 

// wrapper object for folders functions 
FilesManager.prototype.folders = {}; 
FilesManager.prototype.folders._dropFiles = function() { 
    var self = this; 
    // self is an instance of folders {} object, and not an instance of FilesManager 
}; 
+2

將它們按前綴分組,或者通過在源代碼中將它們分開,但不通過嵌套屬性進行分組。 – Bergi

+0

函數類將有大約50個方法,用於「文件夾」,「文件」,「屬性」等,我正在尋找一種方法來組合函數 – Catalin

回答

0

您可以重新使用文件夾的原型,但必須創建文件夾的實例以使用它的FileManager實例的引用。代碼可以看起來像這樣:

function Folders(fileManager){ 
    this.fm=fileManager; 
} 
Folders.prototype._dropFiles=function(){ 
    //test to see if we get the correct name 
    console.log("logging name:",this.fm.name); 
} 
function FilesManager(args) { 
    if(typeof args==="undefined"){ 
    args={}; 
    } 
    this.name=args.name?args.name:"default name"; 
    this.folders=new Folders(this); 
}; 

var fm1=new FilesManager({name:"fm1"}); 
var defaultNamedfm = new FilesManager(); 
fm1.folders._dropFiles(); 
defaultNamedfm.folders._dropFiles();