wogsland wogsland - 3 months ago 11
Javascript Question

Adding subobject to object

I am trying to add a subobject to object like

var myObj = myObj || {};
myObj.prototype.subObj = {
'funk': function() {
console.log('Funky success');
}
};


but I keep getting the error


Uncaught TypeError: Cannot set property 'subObj' of undefined

Answer

If you want to use prototypes, you must create your objects with functions:

function myObj() { }

myObj.prototype.subObj = {
  'funk': function() {
    console.log('Funky success');
  }
};

var obj = new myObj();
obj.subObj.funk(); // => 'Funky success'

But you can always do:

var myObj = {}

myObj.subObj = {
      'funk': function() {
        console.log('Funky success');
      }
    };

myObj.subObj.funk(); // => 'Funky success'
Comments