0

I am attempting to learn how to create classes in Javascript & how to perform object inheritance. I have followed some tutorials but I am not sure if my code is correct.

  • Am I creating public functions & attributes correctly? If not, what should I change?
  • Am I creating privileged functions & attributes correctly? If not, what should I change?
  • Am I creating private functions & attributes correctly? If not, what should I change?
  • Am I overriding functions correctly?
  • Am I performing inheritance correctly?
  • If theres anything wrong can you show me how the code should be?

Heres my simple code that creates a base class then a child class:

/* Base Object Class */
function BaseClass( /*string*/ objType )
{
   /* Public: */
   this.name = "blah";

   BaseClass.prototype.getName = function()
   {
    return this.name;
   }

   BaseClass.prototype.setName = function( newName )
   {
      var oldName = this.name;
      this.name   = newName;

      return oldName;
   }


   /* Private: */
   var attributeMap = {};

   this.constructor = function()
   {
      // this objects default constructor. Is this correct?
      attributeMap["type"]     = objType;
      attributeMap["uniqueID"] = "Base"+(++INSTANCE_COUNT);
   }


   /* Privileged: */
   // Will an object that inherits from this class be able to override the following functions? 
   // Or do I have to make these functions public in order to override them?
   this.toString = function()
   {
      var s = "";
      for (var attrib in attributeMap)
      {
         s += attrib + ": " + attributeMap[attrib] + ", ";
      }
      return s;
   }

   this.getType = function()
   {
      return attributeMap["type"];
   }

   this.renderObject = function()
   {
      // TODO: render object on HTML5 canvas
   }

   this.parseXMLNode = function( /*XML Node*/ nodeXML, /*string*/ objType )
   {
      var attribs = nodeXML.attributes;

      for (var i=0; i<attribs.length; i++)
      {
         attributeMap[ attribs[i].nodeName ] = attribs[i].nodeValue;
      }

      // store children 
      if ( nodeXML.hasChildNodes() )
      {
         attributeMap["children"] = nodeXML.childNodes;
      }

      reformatObjectInnerHTML();
   }

}


// Static Variables //
BaseObject.INSTANCE_COUNT = 0;


// My Child Class //
ChildClass.prototype = new BaseObject( objType );     // make ChildClass inherit from BaseClass
ChildClass.prototype.constructor = function(ObjType)  // Make the ChildClass call the BaseClass constructor
{
   BaseObject.prototype.constructor.call(this, objType);
}

function ChildClass( /*string*/ objType )
{
   /* Privileged: */
   // Attempt to override BaseClass function renderObject()
   this.renderObject = function()
   {
       alert("ChildClass::renderObject();");
       // Does this override the BaseClass renderObject() function?
   }
}
sazr
  • 24,984
  • 66
  • 194
  • 362
  • You realize javascript is a prototype language, not an OO language? – CamelCamelCamel Nov 04 '11 at 23:28
  • yeah I know, I come from C++. I dont really understand whats different though. Although I know that its a prototype language. – sazr Nov 04 '11 at 23:30
  • If you have the time and you like to explore languages try to learn the Io language to wrap your head around prototypical languages. http://iolanguage.com/ – CamelCamelCamel Nov 04 '11 at 23:31
  • 2
    @Radagaisus Those two are not mutually exclusive. JavaScript is an OO language, of course. As a matter of fact, JavaScript is a **prototype-based**, **imperative**, **functional**, **weakly typed**, **object-oriented**, **dynamic**, **scripting language**. `:P` – Šime Vidas Nov 04 '11 at 23:32
  • @ŠimeVidas see http://stackoverflow.com/questions/107464/is-javascript-object-oriented and http://javascript.crockford.com/javascript.html – CamelCamelCamel Nov 04 '11 at 23:35
  • @Radagaisus Both links state that JavaScript is OO. I don't understand what you mean... – Šime Vidas Nov 04 '11 at 23:39
  • imo, you can write a lisp interpreter in c, but it doesn't make c a functional language. – CamelCamelCamel Nov 04 '11 at 23:42
  • Prototype methods don't go in the constructor. There are several patterns you can follow, none is "right" but it could be wrong or just wrong for your implementation. – AutoSponge Nov 05 '11 at 00:45

2 Answers2

2

How to Achieve Private, Public, Privileged members in Javascript

Though I'm not advising you to write code like this. JavaScript is different from C++. Don't write C++ code in JavaScript.

CamelCamelCamel
  • 5,200
  • 8
  • 61
  • 93
0

Seriously inheritance in JS is just not that useful. Copy the functions to another object if you need them there, are just call them in context of that object. I do plenty of OOP in Java land, but inheritance can easily be avoided in javascript through the use context and callbacks. That is if when you think you need an inheritance hierarchy, you probably just need a callback or call the function in a different context.

But to answer your question that is not the "correct" way check out javascript garden

function Foo() {
    this.value = 42;
}
Foo.prototype = {
    method: function() {}
};

function Bar() {}

// Set Bar's prototype to a new instance of Foo
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';

// Make sure to list Bar as the actual constructor
Bar.prototype.constructor = Bar;

var test = new Bar() // create a new bar instance
speajus
  • 46
  • 1
  • `Bar.prototype = new Foo();` is not very good either. It is too restrictive. E.g. you cannot pass along an argument passed to the `Bar` constructor to the `Foo` constructor. – Felix Kling Nov 05 '11 at 02:03