0

This is how I using Object.defineProperties to generate an objct:

var obj = {
    t3: 3,
    t1: Object.defineProperties({}, {
        getT3: {
            value: function () {
                console.log(this.t3);
            }
        },
        t2: {
            value: this.t3
        },
        t3: {
            value: 4
        }
    })
}

Now I want to print the obj.t1.t2 value: console.log(obj.t1.t2), but the return result is undefined

But I can using the obj.t1.getT3() method to obtain the obj.t1.t3's value;

Why the t3 assignment to t2 doesn't work in Object.defineProperties?

DEMO is here: http://jsfiddle.net/HrLLQ/

hh54188
  • 14,887
  • 32
  • 113
  • 184
  • The problem is actually not related to `Object.defineProperties`, but how `this` works in an object literal. – Bergi Jul 31 '14 at 03:53

2 Answers2

1

The problem here is about the this element.

When you call .defineProperties(), the this element does not refer to the object you are in, or it's parent or wathever, but it refers to the this element of the function defineProperties, which is actually window.

Here is an example:

var foo = { bar: 10, b: { c: this, d: this.bar } }
console.log(foo.b.d); // logs undefinded, because the window object has no attribute .bar
console.log(foo.b.c); // logs the window object

function x() { y = this }
x();
console.log(y); // also logs the window object

To make it work you have to define the .t2 property as a function like:

function() { return this.t3 }

So once the object has been created its this element will be obj, and obj.t1.t2() will return obj.t3 (which is actually 3).

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

I think you cannot access this as above. Just define t2 as a function and it should work

var obj = {
    t3: 3,
    t1: Object.defineProperties({}, {
        getT3: {
            value: function () {
                console.log(this.t3);
            }
        },
        t2: {
            value: function(){
                return this.t3;
            }
        },
        t3: {
            value: 4
        }
    })
}

console.log(obj.t1.t2());
obj.t1.getT3();
Mritunjay
  • 25,338
  • 7
  • 55
  • 68