【问题标题】:Can I create a javascript function in EcmaScript 5 with the new get and set in one declaration?我可以在 EcmaScript 5 中使用新的 get 和 set 在一个声明中创建一个 javascript 函数吗?
【发布时间】:2014-11-15 20:04:08
【问题描述】:

我对用作 Angular.js 控制器的 ES5 getter 和 setter 非常感兴趣。目前我正在做:

var helloEC5 = function(){
  //constructor
  this.pants = "jeans";
};
helloEC5.prototype = {
    firstName: 'Seeya',
    lastName: 'Latir',
    get fullName() {
      console.log("get")
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
      console.log('set')
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}; 

但是有没有办法在 function() 中简洁地做到这一点?我真正想要的是(伪代码);

var helloEC5 = function() {
    firstName: 'Seeya',
    lastName: 'Latir',
    get fullName() {
      console.log("get")
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
      console.log('set')
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}; 

【问题讨论】:

标签: javascript angularjs ecmascript-5


【解决方案1】:

您可以使用Object.defineProperty() 方法 (http://jsfiddle.net/ydhLbwg6/):

var helloEC5 = function () {
    this.firstName = 'Seeya';
    this.lastName = 'Latir';
    Object.defineProperty(this, 'fullName', {
        get: function () {
            console.log('get');
            return this.firstName + ' ' + this.lastName;
        },
        set: function (value) {
            console.log('set');
            var words = value.toString().split(' ');
            this.firstName = words[0] || '';
            this.lastName = words[1] || '';
        }
    });
};

【讨论】:

  • 对我来说太罗嗦了,我想知道github.com/Baqend/jahcode 是否是简洁和原生善良之间的良好折衷?
  • 构造函数在哪里?是否有任何标准方法可以将构造函数参数混合为属性?
猜你喜欢
  • 2023-01-30
  • 2016-02-29
  • 2022-01-25
  • 1970-01-01
  • 2023-03-11
  • 2020-08-04
  • 2011-05-22
  • 1970-01-01
相关资源
最近更新 更多