好的,据我所知,我们将像这样编写一个类构造函数
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
//anything outside of constructor belong to this.prototype
getName() {
console.log(this.name);
}
getAge() {
console.log(this.age);
}
}
所以如果我写这样的话:
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
console.log(this.name);
}
}
User.prototype.getAge = function () {
console.log(this.age);
};
从技术上来说应该完全正确吗?还是我错了?因为当我尝试每个时,都会得到2个不同的结果:
let user = new User('john', 23);
let properties = [];
for (let prop in user) {
properties.push(prop);
}
console.log(properties); //The first code result : ["name", "age"]
//The second code result : ["name", "age", "getAge"]
那么两者有什么区别?
类语法只是一个语法糖。
在第二种情况下,您要添加一个名为getAge
的属性。并且它的类型是函数。
两者之间的区别在于,使用User.prototype.getAge = ...
会将属性与属性描述符enumerable: true
相加。这意味着它显示在for...in
循环中。
for...in
语句遍历由字符串键控的对象的所有for...in
(忽略由enumerable properties s键控的对象),包括继承的可枚举属性。
如果要以完全相同的方式定义原型,则必须使用相同的属性描述符。这可以通过class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
console.log(this.name);
}
}
User.prototype.getAge = function () {
console.log(this.age);
};
let user = new User('john', 23);
let properties = [];
for (let prop in user) {
properties.push(prop);
}
console.log(properties);
console.log(Object.getOwnPropertyDescriptor(User.prototype, "getName"));
console.log(Object.getOwnPropertyDescriptor(User.prototype, "getAge"));
:
Object.defineProperty()