0
myObj={
a: 10,
b: this.a
}
console.log('b :',myObj.b)

this gives value of b as undefined. What is the correct way to do this.

akhil xavier
  • 1,847
  • 15
  • 15

5 Answers5

3

You can use the simple way to get that value in a new property of that same object as JavaScript does not work like the way you are expecting,

var myObj={
   a: 10
};
myObj.b = myObj.a;
console.log('b :',myObj.b)
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Your this is currently the global object, which is undefined. You can either create a function (closure) to ensure your this is what you want. Or you can either create a globar var outside that object and assign a property of that object to it.

I'm not sure what you're trying to accomplish though.

If you want an example, you can do for example:

function Person() {
   this.a = 10;
   this.b = this.a; // is this what you want? (why?)
}

Then, you can create a Person typing var x = new Person().

Anyway, what happened here was, I created a javascript closure (aka function) which has its this attribute. Or else this will be undefined (Unless you're on a browser, in that case it will be window, or, if you're on node, it will be the global object).

João Vilaça
  • 601
  • 1
  • 6
  • 13
0

Add a constructor or another function that sets this.b = this.a

Leon Marzahn
  • 341
  • 4
  • 15
-1

try such that

myObj={
a: 10,
b: a
}



var myObj={ 
a: 10,
b:this.c,
c:function() {
this.b=this.a;
     return this.b;
}

look here http://jsfiddle.net/36vfy4yu/

Vinod Ghunake
  • 306
  • 2
  • 7
-1

If you really want to assign a property with a reference to another property INSIDE the same object you are just creating, you can create an object from an anonymous function constructor, like so:

var object = new (function() {
   this.a = 3;
   this.b = this.a;
})()

And then you can reference like so:

console.log(object.a) // 3
console.log(object.b) // 3
filipbarak
  • 1,835
  • 2
  • 17
  • 28
  • [Never ever use `new function`!](https://stackoverflow.com/q/10406552/1048572) – Bergi Feb 21 '18 at 11:49
  • Okay, try to instantiate the function without the new keyword and see if you can log `object.a` or `object.b`. And anyway, the question is specifically how to assign a property referencing another property of the same object that's being declared. – filipbarak Feb 21 '18 at 11:52
  • function SetValues() { var b=null; var myObj={ a: 10, b:this.c, c:function() { this.b=this.a; //alert("a:"+myObj.a); alert("in function b:"+myObj.b); return this.b; } } alert("Out Side b:"+myObj.c()); } – Vinod Ghunake Apr 13 '18 at 07:07