用对象中的某个属性值, 决定对象中的另一个属性的值

let obj = {
  active: false,
  name: 'A',
  type: 'letter',
  subObj: {
    checked: active ? 'yes' : 'no'
  }
}

用对象obj中的active值来决定 对象obj中子对象subObj中checked 的值, 这样写会报 'active' undefined?
会有一个函数方法 动态改变obj中的active的值, 所以想要在改变active的时候, subObj中的checked也跟着改变, 要怎么写判断比较简洁呢?

阅读 2.4k
4 个回答

构造子级对象属性时确实不能直接拿到父级对象的属性。不过像这种对象字面量写法,值都已经确认了,直接把计算后的值给出来就好了。

虽然不能构造子级对象的属性,但是由于这个子级对象是父组对象的属性,直接构造这个对象是可以的。比如下面这个例子:

let obj = {
    active: false,
    name: "A",
    type: "letter",
    get subObj() {
        const checked = this.active ? "yes" : "no";
        return {
            checked
        };
    }
};

当然,对于结构相对复杂的情况,建议还是用 create 函数来构造比较好:

// 这里只用 active 作为参数,也可以根据需要加其他参数
function createObj(active) {
    return {
        active,
        name: "A",
        type: "letter",
        subObj: {
            checked: active ? "yes" : "no"
        }
    };
}

或者干脆直接写类

class Obj {
    active = true;
    name;
    type = "letter";
    subObj;
    constructor(name, active) {
        this.name = name;
        this.active = active;
        this.subObj = { checked: active ? "yes" : "no" };
    }
}

或者如果需要先构建对象,再来完善对象属性(包括子对象之类的),可以使用 validate 函数来验证和修正,比如

let obj = {
    active: false,
    name: "A",
    type: "letter",
};

function validateObj(obj) {
    (obj.subObj ??= {}).checked = obj.active ? "yes" : "no";
}

validateObj(obj);

主要看这个值要怎么用,其实合理的用get 这个读取器方式获取是比较可行的用法。或者同时处理设置器。

class Obj{
   _active = true;
   name;
   type = 'letter';
   subObj = {checked:'yes'};
   constructor(name){
      this.name = name;
   }
   set active( b ){
      this._active = b;
      this.subObj.checked = b? 'yes':'no';
   }
   get active(){
      return this._active;
   }
}

x = new Obj('abc')
x.active = false
console.log(x.active)
console.log(x.subObj.checked)

这里面给你一个小demo
image.png

obj.subObj.__defineGetter__("checked", () => obj.active ? "yes" : "no");
console.dir(obj.subObj.checked);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题