JS ES6类语法和原型混乱

问题描述 投票:1回答:3

好的,据我所知,我们将像这样编写一个类构造函数

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"]

那么两者有什么区别?

javascript prototype
3个回答
0
投票

类语法只是一个语法糖。


0
投票

在第二种情况下,您要添加一个名为getAge的属性。并且它的类型是函数。


0
投票

两者之间的区别在于,使用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()
© www.soinside.com 2019 - 2024. All rights reserved.