0

is it possible to access the current object during creation in javascript?

Example:

var data = {x: 1, z:x}

OR

var data = {x: 1, z: data.x}

This code does acutally not work but i wonder if this is possible somehow?

Thanks in advance.

Freddy
  • 856
  • 2
  • 16
  • 31

1 Answers1

1

By using constructor function

var data = function() {
    if ( !(this instanceof data ) ) {
        return new data();
    }

    this.y = 3;
    this.x = this.y;
}

var obj = new data()

EDIT: Better practice

patrykf
  • 449
  • 5
  • 19