Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 Class #14

Open
RachelRen opened this issue Aug 19, 2018 · 0 comments
Open

ES6 Class #14

RachelRen opened this issue Aug 19, 2018 · 0 comments

Comments

@RachelRen
Copy link
Owner

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 定义方式的差异

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant