Reputation: 7442
I want to create a class in Java Script. I can use basic functions coupled with prototypes but I want to use Object Literal Notation. Is is possible to create classes using Object Literal Notations?
Upvotes: 0
Views: 1015
Reputation: 15789
Cannot be done....well, depends on how you define the params of the requirements. Should be done? Up for debate.
The following is from an idea a coworker of mine had.
http://bit.ly/18xGdKi [JSBin with console example]
if (typeof (makeClass) === "undefined") {
makeClass = function(o) {
var F = function () {};
if (typeof (o) === "object" && o !== null) {
if (typeof (o.constructor) === "function") {
F = o.constructor;
}
F.prototype = o;
}
return F;
};
}
var MyClass = makeClass({
constructor: function (pName) {
var _myPrivateIdaho = 'Idaho ' + pName;
this.name = pName;
var _myPrivateFunc = function() {
console.log('You are in my ' +
_myPrivateIdaho +'.');
};
_myPrivateFunc();
},
getName: function() {
return this.name;
}
});
new MyClass('Bob');
new MyClass('Steve');
Upvotes: 0
Reputation: 22438
You cannot create an instance of an object (and yes, you could even see functions as objects in Javascript, but I'm talking about literal defined objects), you must use a function to define a reusable class.
Upvotes: 2