Reputation: 6052
As everyone should know, in JavaScript there are no actual Classes
.
However, you can use a simple function to make a class like setup.
Ex:
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.
My "class" will have many functions and I want to know if there is a way to do something like (which I know doesn't work):
this = {
fun1: function () {},
fun2: function () {},
fun3: function () {}
}
because I find this doing:
this.fun1 = function(){};
this.fun2 = function(){};
this.fun3 = function(){};
Is quite ugly. Is there a way to keep all my functions in an object and attaching then to this
?
Upvotes: 2
Views: 131
Reputation: 13967
If you don't need to access private members, you can do this:
function Person(){
//stuff
}
Person.prototype = {
fun1:function(){},
fun2:function(){},
//etc
};
You will still be able to access this
from within the prototype functions.
Alternatively, you could do something like this:
function Person(name){
var display = function(){//stuff};
return {
name: name,
fun1: function(){},
fun2: function(){}
};
}
Upvotes: 2
Reputation: 4238
You've essentially got the idea.
In your Person example, simply apply the right context to your getDressed
function:
var that;
var Person = function(name){//class like function
that = this;
};
show = person.prototype.display.call(that, "Hello");
Upvotes: 0
Reputation: 406
You could use $.extend(Person.prototype, yourthisobject);
if you want to keep everything contained in a this object.
Upvotes: 0
Reputation: 23863
You can do this:
var funcs = {
fun1: function () {},
fun2: function () {},
fun3: function () {}
}
// Simple combiner
for (var f in funcs) {
if (funcs.hasOwnProperty(f)) {
this[f] = funcs[f];
}
}
Upvotes: 1