class与prototype

2023-04-20,,

创建实例对象:

ES5中常用的构造函数模式

function Person(name){
    this.name = name;
    
    this.getName = function(){
        return this.name
    }
}

ES6 通过class定义类

class Person{
    constructor(name){
        this.name = name;
    }

    getName(){
        return this.name;
    };
}

1、类的所有方法都定义在类的prototype属性上面

2、类和原型上的方法、属性都是不可枚举的,所以只能通过Object.getOwnPropertyNames(Person/Person.prototype)获取其属性、方法名来遍历;

     注:1)for-in,  Object.keys(),  Object.getOwnPropertyNames三种方式遍历对象

            2)for-in和Object.keys()只能获取可枚举的属性、方法


参考:

http://es6.ruanyifeng.com/#docs/class

《class与prototype.doc》

下载本文的Word格式文档,以方便收藏与打印。