Javascript 为什么一个属性的getter不起作用?
我正在尝试为Person上定义的属性添加getter,以便执行test.fullName。问题是,当我记录test.fullName时,它是未定义的。为什么吸气剂工作正常Javascript 为什么一个属性的getter不起作用?,javascript,getter,Javascript,Getter,我正在尝试为Person上定义的属性添加getter,以便执行test.fullName。问题是,当我记录test.fullName时,它是未定义的。为什么吸气剂工作正常 function Person(name, surname, yearOfBirth){ this.name = name, this.surname = surname, this.yearOfBirth = yearOfBirth }; Object.defineProperty(Person, '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);
您正在定义Person的fullName属性。您应该在Person.prototype上定义它,以便实例继承它:
功能人员姓名、姓氏、出生年份{
this.name=名称;
this.姓氏=姓氏;
this.yearOfBirth=出生年份;
};
Object.definePropertyPerson.prototype“全名”{
get:函数{
返回this.name+''和this.姓氏
}
};
var测试=新人员测试,测试,9999;
console.logtest.fullName 您正在定义Person的fullName属性。您应该在Person.prototype上定义它,以便实例继承它:
功能人员姓名、姓氏、出生年份{
this.name=名称;
this.姓氏=姓氏;
this.yearOfBirth=出生年份;
};
Object.definePropertyPerson.prototype“全名”{
get:函数{
返回this.name+''和this.姓氏
}
};
var测试=新人员测试,测试,9999;
console.logtest.fullName 您必须在Person的prototype属性上定义属性,以便在所有实例上继承该属性
Object.defineProperty(Person.prototype, 'fullName', {
get: function() {
return this.name +' '+ this.surname
}
});
仅向Person添加属性将使其成为静态的。你必须亲自做。你可以在网站上阅读更多。根据链接:
原型是JavaScript对象相互继承特性的机制
因此,要使所有Person实例继承所有属性(如fullName),请在Person.prototype上定义属性
Object.defineProperty(Person.prototype, 'fullName', {
get() {
return `${this.name} ${this.surname}`;
}
});
此外,您使用的是逗号而不是分号。使用分号终止语句,而不是逗号:
this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;
您必须在Person的prototype属性上定义属性,以便在所有实例上继承该属性
Object.defineProperty(Person.prototype, 'fullName', {
get: function() {
return this.name +' '+ this.surname
}
});
仅向Person添加属性将使其成为静态的。你必须亲自做。你可以在网站上阅读更多。根据链接:
原型是JavaScript对象相互继承特性的机制
因此,要使所有Person实例继承所有属性(如fullName),请在Person.prototype上定义属性
Object.defineProperty(Person.prototype, 'fullName', {
get() {
return `${this.name} ${this.surname}`;
}
});
此外,您使用的是逗号而不是分号。使用分号终止语句,而不是逗号:
this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;
在原型上定义它
Object.defineProperty(Person.prototype, 'fullName', {
get() {
return `${this.name} ${this.surname}`;
}
});
在原型上定义它
Object.defineProperty(Person.prototype, 'fullName', {
get() {
return `${this.name} ${this.surname}`;
}
});
@安德鲁利:?你是说当我添加代码片段时-@AndrewLi::-我想知道是否有一个dupetarget来结束这个问题…嗨@T.J.Crowder谢谢你的帮助!还有一点解释。@AndrewLi:?你是说当我添加代码片段时-@AndrewLi::-我想知道是否有一个dupetarget来结束这个问题…嗨@T.J.Crowder谢谢你的帮助!还有一点解释。