es6设置功能未被识别

时间:2017-01-02 12:57:36

标签: javascript ecmascript-6 es6-class

我正在研究es6的新语法,现在我正在查看get和set方法,并且在尝试使用set方法时出现错误

这是片段



class Person {
	constructor(firstName, lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	get fullName() {
		return `${this.firstName} ${this.lastName}`;
	}

	set fullName(...value) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
}

let a = new Person('Person','A');
a.fullName('Person','B')
console.dir(a);




3 个答案:

答案 0 :(得分:2)

getter和setter不用作标准功能。根据MDN:

  

set语法将object属性绑定到要调用的函数   当试图设置该属性时。

您应该使用普通的=赋值来调用setter,而不是将其称为函数。

此外,setter只接受一个参数,并且不能使用rest(...)语法。您可以使用数组或对象,并使用解构赋值来实现此目的。

class Person {

  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  
  set fullName([firstName, lastName]) {
    this.firstName = firstName;
    
    this.lastName = lastName;
  }
}

let a = new Person('Person','A');

a.fullName = ['Person', 'B'];

console.dir(a);

答案 1 :(得分:2)

这不是全新的语法。它是ES5 setter的变体,适用于ES6类。

get / set属性访问器的重点是它们被定义为属性描述符并用作普通属性:

console.log(person.fullName);
person.fullName = 'Foo Bar';

它应该是:

set fullName(value) {
    const [firstName, lastName] = value.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;
}

如果要将其用作普通方法,将其定义为set setter是没有意义的。相反,它可以是

setFullName(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

答案 2 :(得分:0)

您无法使用此类设定器,请参阅下面的我的摘录和see this answer for an explanation



class Person {
	constructor(firstName, lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	get fullName() {
		return `${this.firstName} ${this.lastName}`;
	}

	set fullName(fname) {
        let fn = fname.split(' ');
		this.firstName = fn[0];
		this.lastName = fn[1];
	}
}

let a = new Person('Person','A');
a.fullName = 'Person B';
console.dir(a);