- class Person{
- // 构造
- constructor(x,y){
- this.x = x;
- this.y = y;
- }
- toString(){
- return (this.x + "的年龄是" +this.y+"岁");
- }
- }
- export {Person};
- //index.js
- import {Person} from './Person';
- let person = new Person('张三',12);
- console.log(person.toString());</span>
1,class 初始化定义:
Person 是一个类 , 定义了属性 (x,y) 与方法 toString()
- console.log(typeof Person);//function
- console.log(Person === Person.prototype.constructor);//true
so: 类的数据类型就是函数, 类本身就指向构造函数, 可以理解为: 类就是构造函数 , 因为 es5 的中 [构造函数 === 构造函数. prototype.constructor]
2,class 类的修改与增加属性方法:
构造函数的 prototype 属性, 在 ES6 的 "类" 上面继续存在. 事实上, 类的所有方法都定义在类的 prototype 属性上面, 通过以下方式可是覆盖类中的方法, 当然定义类的时候也可以通过这个方式添加方法.
- Object.assign(Person.prototype,{
- getWidth(){
- console.log('12');
- },
- getHeight(){
- console.log('24');
- }
- });
- Person.prototype.sex = 'man' ;
- console.log(p.sex); // man
- Person.prototype.sex = 'woman' ;
- console.log(p.sex); //woman
- //class 拥有保护机制, 可以增加, 或覆盖原来有属性, 但是如下就不行
- Person.prototype == {}
- console.log(p.sex); //'woman';
- //sex 属性还在, prototype 从新赋空值这样是不生效的
PS 建议: class 类已经定义完毕不可修改, 不可直接修改 Person.prototype, 个别场景需要, 应新建一个继承 class 上, 然后再修改, 拓展, 新 class 继承老的 class
来源: http://www.bubuko.com/infodetail-2613599.html