大家應該知道,在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
?
我想你的意思是this.getDressed公衆,對不對? – Igor
哎呀,是的,這就是我的意思。我改變了這一點。 – Shawn31313
我發現這種方法很有趣:http://ejohn.org/blog/simple-javascript-inheritance/ –