What is the difference between prototype-based class syntax and class syntax in JavaScript?

前端 未结 2 1050
囚心锁ツ
囚心锁ツ 2020-12-04 02:13

Are these interchangeable syntax\'s to create a JS class? I\'m used to the class syntax but don\'t understand the differences between them exactly.

2条回答
  •  眼角桃花
    2020-12-04 02:57

    From MDN:

    JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

    You can use a tool like the Babel REPL to see how the ES6, class-based code you have above is then transpiled into ES5, prototype-based code:

    ES6 Class

    class User {
    
     constructor(name) {
       this.name = name;
     }
    
     sayHi() {
       alert(this.name);
     }
    
    }
    
    let user = new User("John");
    user.sayHi();
    

    Transpiled to ES5

    "use strict";
    
    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; }; }();
    
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    
    var User = function () {
      function User(name) {
        _classCallCheck(this, User);
    
        this.name = name;
      }
    
      _createClass(User, [{
        key: "sayHi",
        value: function sayHi() {
          alert(this.name);
        }
      }]);
    
      return User;
    }();
    
    var user = new User("John");
    user.sayHi();
    

    All ES6+ functionality will be able to be transpiled into ES5-- it is all, effectively, syntactic sugar. All "new features" can still be achieved in ES5. This is called, I believe, the "One JavaScript" doctrine.

提交回复
热议问题