对ES6 class的一些理解

122 阅读1分钟

一 、class的作用

  1. 封装一组数据和对数据的操作
 比如想对字符串进行操作
 class TransformStr {
   constructor(str) {
     this.str = str
   }
   getStr() {
    return this.str;
   }
   repeatStr(time) {
     return this.str.repeat(time)
   }
 }
 
 var str = new TransformStr('123')
 str.getStr(); // 123
 str.repeatStr(2) // 123123
 
  1. 更好的实现继承
class ParentStr  {
   constructor(str) {
     this.str = str
   }
   getStr() {
    return this.str;
   }
   repeatStr(time) {
     return this.str.repeat(time)
   }
 }
 
 class ChildStr extends ParentStr {
   constructor(str, num) {
     super(str)
     this.num = num
   }
   getStr() {
    return this.str;
   }
   getNum() {
    return this.num;
   }
   repeatStr(time) {
     return this.str.repeat(time)
   }
 }
 
 var m = new ChildStr('str', 123)
 m.getStr() // 'str'
 m.getNum() // 123

二、class的简单实现

class的基本实现原理和构造函数是一样的,都是通过原型链的方式,其实就是把构造函数prototype上的方法放到了class内部

// 检查是否通过new调用
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
   throw new TypeError('Cannot call a class as a function');
  }
}

// 在原型上添加属性
function _createClass(Constructor, protoProps = [], staticProps) {

  _defineProperties(Constructor.prototype, protoProps);
  _defineProperties(Constructor, staticProps);

}

function _defineProperties(target, props) {
  props.forEach(prop => Object.defineProperty(target, prop.key, prop))
}
// 通过原型链的方式实现继承
function _inherits(subClass, superClass) {
  subClass.prototype = Object.create(superClass);
  subClass.prototype.constructor = subClass;
  Object.defineProperty(subClass, superClass);
}

// class实现过程
var Person = (function() {
  function Person(options) {
    _classCallCheck(this, Person);

    this.name = options.name;
    this.age = options.age;
  }
    _createClass(Person, [{
      key: 'eat',
      value: function eat() {
        return 'eating'
      }
    }], [{
        key: 'isPerson',
        value: function isPerson(instance) {
          return instance instanceof Person
        }
      }]
    );
  
  return Person;
})()

// 继承实现过程
var Student = (function(_Person) {
  

  function Student(options) {
    _classCallCheck(this, Student)

    _Person.call(this);

    this.grade = options.grade;
  }

  _createClass(Student,
    // 实例属性方法
    [{
      key: 'study',
      value: function study() {
        return 'studying'
      }
    }],
    // 静态属性方法
    [{
      key: 'isStudent',
      value: function isStudent(instance) {
        return instance instanceof Student
      }
    }]
  )

  return Student;
})()

var p = new Person({name: 'li', age: 20});
console.log(p.isPerson());