class与prototype

创建实例对象:

ES5中常用的构造函数模式

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

捕获.PNG


ES6 通过class定义类

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

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

捕获.PNG

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

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

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


参考:

扫描二维码关注公众号,回复: 6868855 查看本文章

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


猜你喜欢

转载自blog.51cto.com/8898126/2423317