Marc Andre Jiacarrini Marc Andre Jiacarrini - 6 months ago 10
Javascript Question

Object creation not responding

I am trying to create a new object here.
Here is my code

function createAnObject(name, address) {
var newObj = new Object();
newObj.name = name;
newObj.address = address;
newObj.saySomething = function () {
console.log("the name is" + this.name + " the addess is" + this.address)
}
}


var ballack = createAnObject('ballack', 'Ndri');
console.log(ballack.name);


but in console the error is

Uncaught TypeError: Cannot read property 'name' of undefined


I am confused here. Could someone tell me where I am going wrong.

Answer

You forgot to return your newObj in your createAnObject function:

function createAnObject(name, address) {
  var newObj = new Object();
  newObj.name = name;
  newObj.address = address;
  newObj.saySomething = function () {
    console.log("the name is" + this.name + " the addess is" + this.address)
  }

  return newObj;
};

var ballack = createAnObject('ballack', 'Ndri');
console.log(ballack.name);  // Now outputs 'ballack'