0

Given this code:

var myObj = new Object({
data: {
    val_a: 1, 
    val_b: 2
},

myfuncs: {
    first_func: function() {
        this.data.val_b = 3;
    }
}
});

why does this fail:

myObj.myfuncs.first_func()

with error:

VM154:9 Uncaught TypeError: Cannot set property 'val_b' of undefined at Object.first_func (:9:20) at :1:15

but this works:

myObj.data.val_b

And what's the correct way to access data.val_b from first_func?

oshi2016
  • 655
  • 1
  • 6
  • 18
  • `this.data.val_b = 3;` is not using the right context, `this` is related to first_func's context rather than myObj's context. – Ele Jan 02 '18 at 13:26
  • Possible duplicate of [Self-references in object literal declarations](https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – gaurav Jan 02 '18 at 13:32

2 Answers2

2

Because in the call to first_func, this refers to myObj.myfuncs, not myObj. More: How does the “this” keyword work?

Since your object is a one-off, you can just use myObj instead:

var myObj = {
  data: {
    val_a: 1,
    val_b: 2
  },
  myfuncs: {
    first_func: function() {
      myObj.data.val_b = 3;
    }
  }
};
myObj.myfuncs.first_func();
console.log(myObj.data.val_b); // 3

(Note that the call to new Object is neither necessary or desirable. Just use the result of the object initializer ({...}) directly.)

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
1

A way to achieve access to this. is to use Arrow function which does not create its own this.
In your example first_func: function() { created a new this.

var myObj = new Object({
  data: {
    val_a: 1,
    val_b: 2
  },
  myfuncs: {
    first_func: () => {
      this.myObj.data.val_b = 3;
    }
  }
});
myObj.myfuncs.first_func();
console.log(myObj.data.val_b); // 3
Olezt
  • 1,338
  • 1
  • 13
  • 29