Javascript:混淆Object.defineProperties函数

Javascript: Confuse about Object.defineProperties function

本文关键字:defineProperties 函数 Object 混淆 Javascript      更新时间:2023-09-26

这是我如何使用Object.defineProperties生成一个对象:

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

现在我想打印obj.t1.t2值:console.log(obj.t1.t2),但返回结果是undefined

但是我可以使用obj.t1.getT3()方法来获得obj.t1.t3的值;

为什么t3赋值给t2不能在Object.defineProperties中工作?

DEMO在这里:http://jsfiddle.net/HrLLQ/

这里的问题是关于this元素。

当您调用.defineProperties()时,this元素不指向您所在的对象,也不指向它的父对象或其他对象,而是指向函数definePropertiesthis元素,实际上是window

下面是一个例子:

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

要使其工作,您必须将.t2属性定义为如下函数:

function() { return this.t3 }

所以一旦对象被创建,它的this元素将是obj,而obj.t1.t2()将返回obj.t3(实际上是3)。

我认为你不能像上面那样访问this。只要把t2定义为一个函数,它就可以工作了

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();
相关文章:
  • 没有找到相关文章