Skip to content

ES6 Class #14

Open
Open
@RachelRen

Description

@RachelRen

class 其实也只是函数的一个语法糖,但是他和普通函数还是有所区别的。

在js中很重要的两点:

  1. 一切都是对象
  2. 函数是一等公民, 还具有属性的特殊对象

class A {
	print () {
    	console.log('print a');
    }
}

经过babel转换后


var A = function () {
   function A() {
      _classCallCheck(this, A);
   }

   _createClass(A, [{
      key: 'print',
      value: function print() {
         console.log('print a');
      }
   }]);

   return A;
}();

可以看出 Class A 也就是一个函数,但是不能当作一个普通函数来调用,因为_classCallCheck 的作用

function _classCallCheck(instance, Constructor) { 
    if (!(instance instanceof Constructor)) { 
        throw new TypeError("Cannot call a class as a function"); 
    } 
}

A() // throw a error
const a = new A(); // work well

关于_createClass

var _createClass = function () { 
  function defineProperties(target, props) { 
    for (var i = 0; i < props.length; i++) { 
      var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; 
      descriptor.configurable = true; 
      if ("value" in descriptor) descriptor.writable = true; 
      Object.defineProperty(target, descriptor.key, descriptor); 
    } 
  } 
  return function (Constructor, protoProps, staticProps) { 
    if (protoProps) defineProperties(Constructor.prototype, protoProps); 
    if (staticProps) defineProperties(Constructor, staticProps); return Constructor; 
  }; 
}();

这个函数的功能是通过Object.defineProperty 定义了类的普通属性和静态属性。普通函数是定义在类的原型对象上,静态属性是定义在类本身上。

与普通函数的区别

this 的绑定

普通函数是绑定在类的原型对象上的,但是箭头函数是直接绑定在类的实例对象上。

继承

class B {
    print = () => {
    	console.log('print b');
    }
}

class D extends B {
    print () {
	  super.print();
          console.log('print d');
    }
}

其实主要是箭头函数的区别

var B = function B() {
   _classCallCheck(this, B);

   this.print = function () {
      console.log('print b');
   };
};

ES6 Class Methods 定义方式的差异

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions