Reputation: 12179
I've got a javascript object which will often need to be initialised with 5 + variables, I don't think using a bunch of setters for each variable every time a new Person
object is created would be nice. A constructor perhaps? How can I put a constructor into my module object? I've found an example of how to write constructors in javascript but I'm not sure if it fits in with how this object is designed: Constructors in JavaScript objects
I'd like to be able to initialise each Person with variables to set Person's privates:
var p = new Person(a, b, c, d, e);
My object:
var Person = (function() {
// private
var name;
var gender;
var weight;
var location;
return {
// public
myfunc: function() {
}
}
})();
Upvotes: 0
Views: 187
Reputation: 27205
var Person = function(name) {
var gender = "male";
this.changeName = function(newName) {
name = newName;
};
this.displayName = function() {
return "<p>" + name + "</p>";
};
this.displayGender = function() {
return "<p>" + gender + "</p>";
};
}
var bart = new Person("Bart");
document.body.innerHTML = bart.displayGender();
This solution is based on the "closure" inheritance model (http://javascript.crockford.com/private.html)
For the prototypal inheritance model, refer to SReject's solution. Note that it doesn't allow true private members.
Upvotes: 1
Reputation: 1284
This pattern will provide you with encapsulated data (hidden fields) and give you easy control over how they are publicly accessed:
var PersonFactory = {
create: function (nm, gn, wt, loc) {
var name = nm,
gender = gn,
weight = wt,
location = loc;
return function (method, arg) {
if (method === 'isName') {
if (name === arg) {
return true;
} else {
return false;
}
} else if (method === 'isFemale') {
if (gender === arg) {
return true;
} else {
return false;
}
}
}
}
};
var chris = PersonFactory.create("Chris", "male", 210, "Pluto");
chris('isName', 'Chris'); // returns true
var jane = PersonFactory.create("Jane", "female", 160, "Alpha Centauri");
jane('isName', 'Jane'); // returns true
jane('isName', 'Chris'); // returns false
I hope this is what you are looking for. Keep in mind, only function objects can hide data, which isn't so bad cause you can access that data with the immaFunciton('methodName', 'args') pattern in a pretty simple manner.
Good Luck, Chirs
Upvotes: 1
Reputation: 3936
Like this:
function Person(a,b,c,d,e) {
this.name = a;
this.gender = b;
this.weight = c;
this.location = d
this.whatever = e;
}
Person.prototype.myName = function () { return this.name; }
Person.prototype.myGender = function () { return this.gender; }
var p = new Person("John", "male", 180, "USA", "Something");
p.myName();
p.myGender();
This uses JS's internal object&inheritance model, so you'd set the individual object's unique variables while in-comman functions and methods would only be specified/created once and all instances of the "Person" object would then use those
Upvotes: 2