You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS组件构造函数中Object.assign转扩展运算符的等价写法

用扩展运算符替代Object.assign的构造函数写法

嘿,这个问题挺实用的!我来给你捋捋怎么用扩展运算符替代现有的写法~

首先先回顾下你当前的代码:

constructor($q, $state) { 
  'ngInject'; 
  Object.assign(this, { $q, $state }); 
}

这段代码通过Object.assign把{ $q, $state }里的属性逐个挂载到组件实例this上,效果和手动写this.$q = $q; this.$state = $state;完全一致。

如果要用**扩展运算符(Spread Operator)**来替代,其实可以直接结合Object.assign来写,写法如下:

constructor($q, $state) { 
  'ngInject'; 
  // 扩展运算符替代写法
  Object.assign(this, { ...{ $q, $state } });
}

这里的...{ $q, $state }就是把这个对象的所有属性展开,再通过Object.assign合并到this上,和原代码逻辑完全等价。

要是你想更简洁一点,还可以用解构赋值结合扩展的思路(不过可读性稍弱一些):

constructor($q, $state) { 
  'ngInject'; 
  ({ ...this, $q, $state } = this);
}

这里要提一句,对象扩展运算符是ES2018的语法特性,不过Angular项目一般通过TypeScript或者Babel编译,所以基本不用担心兼容性问题。如果后续需要合并多个对象到this上,扩展运算符的优势会更明显,比如:

Object.assign(this, { $q }, { $state }, ...otherDependencyObjects);

内容的提问来源于stack exchange,提问作者Mouad Ennaciri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:17:05