-1

Is it possible to assign a value to an object property using a property of the current object being decalred?

var myObject = new Object({ 
    a: 1, 
    b: 2, 
    c: this.a + this.b // is this possible ? ( or even myObject.a + myObject.c)
});

I know I could just declare it as below but is it possible as above?

myObject.c = myObject.a + myObject + b;
Ian Brindley
  • 2,197
  • 1
  • 19
  • 28

1 Answers1

1

A simple console log should have shown you why your code works but gives a NaN. After modifying your code to the sample below and running it:

var myObject = new Object({
     a: 1,
     b: 2,
     c: console.log(this.a + this.b)
});
myObject.c;

the result was: NaN why? When you created myObject this was bound to the document object which apparently doesn't have properties a and b.Perhaps this will work for you:

var myObject = new Object({
     a: 1,
     b: 2,
     c: function () {
         return this.a + this.b;
     }
});
myObject.c();

Check this out question: stackoverflow.com/questions/133973/ to understand more about this within a javascript object literal

Community
  • 1
  • 1
Tafadzwa Gonera
  • 352
  • 6
  • 20