繁体   English   中英

Object 分配和 Object 传播之间的不同结果

[英]Different outcomes between Object assign and Object spread

我正在使用 typescript 并编译为 ES2016。 我注意到我在Function.prototype.call()中调用了两个具有类似this的不同函数。 我试图通过使用一个常见的 object 来合并this两个对象,这将使用...spread在 object 的开头,就像这样

let selfShared = {
  props,
  // ...
};

let selfHost = {
  ...selfShared,
  // ...
};

let selfGuest = {
  ...selfShared,
  // ...
};

在乞求中使用传播的想法是,如果我认为合适,我可以覆盖任何一个this对象中的共享属性。 但与使用 spread 直接在this对象中设置props不同,会产生奇怪的结果,这是因为tsc将代码编译为

let selfShared = {
  props
};

let selfHost = Object.assign(Object.assign({}, selfShared), {
  // ...
});

// ...

使用我的代码

let state = undefined;
let attributes = {};
let selfShared = {
  props: attributes
};

let selfHost = {
  ...selfHost,
  get state() {
    console.log("selfHost get state");
    return state;
  },
  set state(originalStates) {
    console.log("selfHost set state");
    !state ? state = originalStates : console.error("`this.states` already defined in the host function.");
  }
}

output 看起来像

let state = undefined;
let attributes = {};
let selfShared = {
  props: attributes
};

let selfHost = Object.assign(
  Object.assign({}, selfShared), {
  get state() {
    console.log("selfHost get state");
    return state;
  },
  set state(originalStates) {
    console.log("selfHost set state");
    !state ? state = originalStates : console.error("`this.states` already defined in the host function.");
  }
});

现在至少在 firefox 74 到 77 上将两个代码插入控制台并添加

// ...
selfHost.state = {
  thing: "some"
};
selfHost.state = {
  some: "thing"
};

抛出不同的日志......预编译的代码给了我两个set state和一个错误,这是预期的输出,但编译的代码给了我一个get state并忽略set state中的规则

{
  some: "thing"
}

而不是预期的

{
  thing: "some"
}

就像在预编译的代码中一样?

将展开设置到文件的底部编译为

let selfHost = Object.assign({
  get state() {
    console.log("selfHost get state");
    return state;
  },
  set state(originalStates) {
    console.log("selfHost set state");
    !state ? state = originalStates : console.error("`this.states` already defined in the host function.");
  }
}, selfShared);

这给出了正确的 output 但不允许我覆盖selfShared给出的属性。

你能解释一下为什么Object.assign会发生这种情况吗?如果有一个技巧可以从tsc获得 output 仍然让我做我最初想做的事情?

使用传播时

let obj = {
  ...otherObj,
  // ...
}

或者

let obj = Object.assign({}, otherObj, {
  // ...
})

spread 被解释为字面量,这意味着在 polyfill 中,属性被读取为严格值,这意味着正常值被正常读取,setter 被忽略,getter 被读取为正常值。

当价差最后写为

let obj = {
  // ...
  ...otherObj
}

或者

let obj = Object.assign({
  // ...
}, otherObj)

因为otherObj只扩展了唯一的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM