我想使用可选的更改运算符 (?.) 来增加对象值。在我的示例中,仅当为当前人设置了年龄时,我才想在名为birthday()的函数中将人的年龄增加一。带有 if 子句的行可以正常工作(也可以明显地使用十进制 if )。不过我想知道类似下面的行是否可能。给定的语法会导致语法错误:无效的递增/递减操作数。也许这是一个基于运算符优先级的问题,但我现在知道如何解决它。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let peter = new Person("Peter", 27);
let paul = new Person("Paul", undefined);
Person.prototype.birthday = function() {
if (this.age) this.age++;
};
//Person.prototype.birthday = function(){this?.age++};
peter.birthday();
paul.birthday();
console.log(peter, paul);Run Code Online (Sandbox Code Playgroud)