对象,其中一个键为默认值(getter/setter)

Object with one key as default (getter/setter)

本文关键字:默认值 getter setter 一个 对象      更新时间:2023-09-26

我知道有了所有新的ECMAScript6,我们正在发生一些令人惊叹的事情。我的目标是做这样的事情,我不知道这是否可能:

var angEl = {
  get(): blah,
  scope: this.scope(),
  injector: this.injector()
}

现在我这样做:

var angEl = blah;
var angElProps = {
  scope: angEl.scope(),
  injector: angEl.injector()
}

只是想知道是否有什么很酷的新时尚方式来接受这一点。

我读到两件事,你想要赋值和方法。

在ES5中实现这一点的最佳方法是将其值放入构造函数中,该构造函数将在运行新的MyObject(value)时运行。然后将这些方法分配给原型。如果你把这些方法放在构造函数中,它可能会导致同一个函数一次又一次地被创建的问题。

ES5

var MyObject = function(value){
    this.value = value;
}
MyObject.prototype.func = function(){};

当您不打算手动编辑对象原型,只想要一个类状对象时,ES6具有更简洁的语法。

ES6

class MyObject{
 constructor(value){
   this.value = value;
 }
 func(){}
}

编辑:此外,ES6内置了get和set。

class MyObject{

     func(){}
     set value(value){
         this._value = value;
     }
     get value(){
         return this._value;
     }
}

不完全是es6,但听起来你想使用Object.defineProperty()或Object.defineProperties()之类的东西。例如:

var angEl = {};
Object.defineProperties(angEl, {
  'scope': {
    get: function() {
      return this.scope;
    },
    set: function(val) {
      this.scope = val;
    },
    value: //set to something
  },
  'injector': {
    ...
  }
});

通过这种方式,您可以在不需要额外对象的情况下,在内部准确地定义如何与对象交互。