2013-01-17 35 views
2

大家應該知道,在JavaScript中沒有實際的Classes使用對象在JavaScript中添加多個「公共函數」

但是,您可以使用一個簡單的函數來設置類。

例:

var Person = function(name){//class like function 
    this.name = name;//public 

    var display = function(text){//private 
     return text; 
    } 

    this.getDressed = function(){//public 
     return display(this.name + " needs to get dressed."); 
    } 

}; 
var person = new Person("John"), 
    name = person.name,//returns "John" 
    dressed = person.getDressed();//returns "John needs to get dressed", 
    show = person.display("Hello");//throws error "Uncaught TypeError: Object [object Object] has no method 'display'" because there is no such function because it was private. 

我「下課」將有很多的功能,我想知道是否有辦法做到像(我知道不工作):

this = { 
    fun1: function() {}, 
    fun2: function() {}, 
    fun3: function() {} 
} 

,因爲我覺得這是這樣做的:

this.fun1 = function(){}; 
this.fun2 = function(){}; 
this.fun3 = function(){}; 

是相當難看。有沒有辦法將我的所有功能都保存在一個對象中,然後附加到this

+0

我想你的意思是this.getDressed公衆,對不對? – Igor

+1

哎呀,是的,這就是我的意思。我改變了這一點。 – Shawn31313

+0

我發現這種方法很有趣:http://ejohn.org/blog/simple-javascript-inheritance/ –

回答

0

你基本上已經明白了。

在你的人例如,簡單地正確的背景下適用於您的getDressed功能:

var that; 
var Person = function(name){//class like function 
    that = this; 
}; 
show = person.prototype.display.call(that, "Hello"); 
1

你可以這樣做:

var funcs = { 
    fun1: function() {}, 
    fun2: function() {}, 
    fun3: function() {} 
} 

// Simple combiner 
for (var f in funcs) { 
    if (funcs.hasOwnProperty(f)) { 
    this[f] = funcs[f]; 
    } 
} 
+0

不知道這是否是最好的主意。由於性能。 – Shawn31313

+0

確實如此,但它確實直接回答了OP的問題。 –

0

你可以使用$.extend(Person.prototype, yourthisobject);如果你想保留一切包含在一個這個對象。

+0

我沒有使用庫。 – Shawn31313

2

如果您不需要訪問私有成員,你可以這樣做:

function Person(){ 
    //stuff 
} 

Person.prototype = { 
    fun1:function(){}, 
    fun2:function(){}, 
    //etc 
}; 

您仍然能夠從原型函數中訪問this

或者,你可以做這樣的事情:

function Person(name){ 
    var display = function(){//stuff}; 

    return { 
     name: name, 
     fun1: function(){}, 
     fun2: function(){} 
    }; 
} 
相關問題