繁体   English   中英

为什么此吸气剂不能用于房地产工作?

[英]Why doesn't this getter for a property work?

我正在尝试为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);

您必须在Personprototype属性上定义该属性,以便在所有实例上继承该属性。

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

仅向Person添加属性将使其静态。 您必须在Person.prototype上执行此Person.prototype 您可以在MDN上阅读更多内容。 每个链接:

原型是JavaScript对象彼此继承特征的机制

因此, Person.prototype所有Person实例继承所有属性(例如fullName ,请在Person.prototype上定义属性。

另外,您使用逗号代替分号。 使用分号来终止语句,而不是逗号:

this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;

您要在Person上定义fullName属性。 您应该在Person.prototype上定义它,因此它被实例继承:

 function Person(name, surname, yearOfBirth) { this.name = name; this.surname = surname; this.yearOfBirth = yearOfBirth; }; Object.defineProperty(Person.prototype, 'fullName', { get: function() { return this.name + ' ' + this.surname } }); var test = new Person("test", "test", 9999); console.log(test.fullName); 


旁注:不要在应带有分号的地方使用逗号,如Person构造函数中那样。 我也已将其修复。

在原型上定义它。

Object.defineProperty(Person.prototype, 'fullName', {
    get() {
        return `${this.name} ${this.surname}`;
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM