为什么这个物业的吸气剂不起作用?

Din*_*vic 1 javascript getter

我正在尝试为定义的属性添加一个getter Person,所以我可以这样做test.fullName.问题是,当我记录时test.fullName,它是未定义的.为什么吸气剂正常工作?

function Person(name, surname, yearOfBirth){
this.name = name,
this.surname = surname,
this.yearOfBirth = yearOfBirth };

Object.defineProperty(Person, 'fullName', {
    get: function(){
        return this.name +' '+ this.surname
    }
});

var test = new Person("test", "test", 9999);
console.log(test.fullName);
Run Code Online (Sandbox Code Playgroud)

Li3*_*357 5

你必须定义的属性Person原型属性,所以它继承了所有实例.

Object.defineProperty(Person.prototype, 'fullName', {
    get: function() {
        return this.name +' '+ this.surname
    }
});
Run Code Online (Sandbox Code Playgroud)

添加属性Person将使其成为静态.你必须这样做Person.prototype.您可以在MDN上阅读更多内容.根据链接:

原型是JavaScript对象相互继承功能的机制

因此,对于所有Person实例继承所有属性,例如fullName,定义属性Person.prototype.

此外,您使用逗号而不是分号.使用分号终止语句,而不是逗号:

this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;
Run Code Online (Sandbox Code Playgroud)