Vanice
Vanice

Reputation: 676

ReferenceError: Object prop not defined

I have the following JavaScript:

var calc = {
    getMem: function(){
        return mem;
    },

    mem:0,

    add: function (a,b){
        mem =  a*b;
        return a*b;
    },
}

When I call

calc.getMem();

right after away I get a ReferenceError

However, when I call

calc.add(3,2);
calc.getMem();

I receive the desired result.

Obviously I was missing the this so I changed my getMem to

getMem: function(){
    return this.mem;
}

My Question is: Why does it work in the inital state (without this) when I first call add?

Upvotes: 2

Views: 170

Answers (3)

Luca Kiebel
Luca Kiebel

Reputation: 10096

calc is not a class, this is not how you set values of an object, if you add a console.log() inside off add you can see, that mem is undefined there, so the line

mem =  a*b;

sets a global variable named mem to a*b, instead of a local value,

calc = {
    getMem: function(){
        return mem;
    },

    mem:0,

    add: function (a,b){
	console.log(mem)
        mem =  a*b;
        return a*b;
    },
}

calc.add(0,0)

You have to set it with this.mem:

"use strict";    

const calc = {
    getMem: function(){
        return this.mem;
    },

    mem:0,

    add: function (a,b){
        this.mem =  a*b;
        return a*b;
    },
}

calc.add(2,3)
console.log(calc.getMem())

And also return this.mem in the getMem function

Upvotes: 2

Mark
Mark

Reputation: 92450

When you call cal.add you are creating a global variable mem. So it seems like it works because getMem is then trying to access that global. But it is probably not what you want. If you call getMem() before add() it is still trying to access the global mem, but it hasn't been defined yet, hence the error.

var calc = {
  getMem: function(){
      return mem;
  },

  mem:0,

  add: function (a,b){
      mem =  a*b;
      return a*b;
  },
}
calc.add(2, 4)
console.log(mem) // available globally

Upvotes: 2

amrender singh
amrender singh

Reputation: 8239

When you call your function getMem() it is unable to find any local or global variable with the name mem that is why you get a reference error. When you execute your add() function it creates a variable mem in the global scope, so now when you call getMem() global variable mem is being returned.

Execute the program in strict mode and you will get reference error.

"use strict"
var calc = {
  getMem: function(){
      return mem;
  },

  mem:0,

  add: function (a,b){
      mem =  a*b;
      return a*b;
  },
}
calc.add(2, 4)
console.log(mem) 

Upvotes: 1

Related Questions