关于文字对象,也许还有自动执行函数

About literal objects and, perhaps, auto executable functions

本文关键字:函数 执行 也许 于文字 文字 对象      更新时间:2023-09-26
var a = {
    b: {
        c: 1
    },
    d: this.b.c
};
错误:

this.b is undefined

我怎么打电话给b.c?

var a = {
    b: {
        c: 1
    }
};
a.d = a.b.c;

是唯一的方法。this.b.c在构建a对象的作用域中执行,而不是在对象本身中执行;因此this = window, window.b == undefined

虽然Matt告诉你只有一种方法,但这可能是另一种选择:

var a = {
  b: {c: 1},
  d: function(){return this.b.c;}
}
alert(a.d()); //=> 1

var a = {
  b: {c: 1},
  d: function(){if (this.d instanceof Function) {this.d = this.b.c;}}
}
a.d();
alert(a.d); //=> 1

或执行匿名函数:

var a = function(){
      var obj ={b: {c: 1}}
      obj.d = obj.b.c;
      return obj;
}();
alert(a.d); //=> 1