0

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?

2 Answers 2

2

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.

0

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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.