众所周知,在JavaScript中没有实际的Classes
。
但是,您可以使用一个简单的函数来创建类似安装的类。
例如:
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 :(得分: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(){}
};
}
答案 1 :(得分:1)
你可以这样做:
var funcs = {
fun1: function () {},
fun2: function () {},
fun3: function () {}
}
// Simple combiner
for (var f in funcs) {
if (funcs.hasOwnProperty(f)) {
this[f] = funcs[f];
}
}
答案 2 :(得分:0)
你基本上已经有了这个想法。
在您的Person示例中,只需将正确的上下文应用于getDressed
函数:
var that;
var Person = function(name){//class like function
that = this;
};
show = person.prototype.display.call(that, "Hello");
答案 3 :(得分:0)
如果您想保留此对象中包含的所有内容,则可以使用$.extend(Person.prototype, yourthisobject);
。