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?

2
  • this.data.val_b = 3; is not using the right context, this is related to first_func's context rather than myObj's context. Commented Jan 2, 2018 at 13:26
  • Possible duplicate of Self-references in object literal declarations Commented Jan 2, 2018 at 13:32

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.