编程语言
首页 > 编程语言> > 我可以在EcmaScript 5中使用新的get和set在一个声明中创建一个javascript函数吗?

我可以在EcmaScript 5中使用新的get和set在一个声明中创建一个javascript函数吗?

作者:互联网

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

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] || '';
    }
}; 

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

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] || '';
    }
}; 

解决方法:

您可以使用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] || '';
        }
    });
};

标签:javascript,angularjs,ecmascript-5
来源: https://codeday.me/bug/20190830/1768389.html