0

I'm getting undefined In place of name

var obj = { name:'Alex', age:27, info:'my name is'+this.name } console.log(obj['info']) Output My name is undefined I'm getting undefined in place of name. How to get the name ??

15th Dec 2022, 10:15 AM
Levi
Levi - avatar
3 Answers
+ 3
That is an object literal and as stated in the "this" MDN article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this Object literals don't create a this scope — only functions (methods) defined within the object do. Using this in an object literal inherits the value from the surrounding scope. const obj = { a: this, }; console.log(obj.a === window); // true Also read the following: https://errorsandanswers.com/access-javascript-object-literal-value-in-same-object-duplicate/ https://stackoverflow.com/questions/13104949/can-one-set-multiple-properties-inside-an-object-literal-to-the-same-value There are some ways to get a workaround but its up to you, what suits you better.
15th Dec 2022, 12:15 PM
arturop200
arturop200 - avatar
+ 1
In the object literal that you have defined, the this keyword refers to the object that is being created, but at the time that the object is being created, the name property has not yet been assigned a value. Therefore, when you try to access this.name, you get undefined. One way to fix this would be to use the object's name property directly, like this: var obj = { name: 'Alex', age: 27 }; obj.info = function() { return 'my name is ' + this.name; } console.log(obj.info());
24th Dec 2022, 8:43 AM
CalviŐČ
CalviŐČ - avatar