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