众所周知,在 JavaScript 中没有实际的Classes
.
但是,您可以使用一个简单的函数来创建一个类似于 setup 的类。
前任:
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
?