Javascript实现继承的几种方式

113 阅读2分钟

借用构造函数

function Animal(name){
  this.name = name
  this.say = function(){
    console.log(`I'm ${this.name}`)
  }
}


function Cat(name){
  Animal.call(this,name) // 借用构造
}

const cat = new Cat("喵")
console.log(cat.say())

对象冒泡

function Animal(name) {
  this.name = name;
  this.say = function () {
    console.log(`I'm ${this.name}`);
  };
}

function Cat(name) {
  // Animal.call(this, name);
  this.animal = Animal
  this.animal(name)
}

const cat = new Cat("喵");
console.log(cat.say());

组合继承

function Animal(name) {
  this.name = name;
}

Animal.prototype.say =function(){
  console.log(`I'm ${this.name}`)
}

function Cat(name) {
  Animal.call(this, name);
}

Cat.prototype = new Animal()

const cat = new Cat("喵");
console.log(cat.say());

寄生组合模式

function Animal(name) {
  this.name = name;
}

Animal.prototype.say =function(){
  console.log(`I'm ${this.name}`)
}

function Cat(name) {
  Animal.call(this, name);
}

Cat.prototype = Object.create(Animal.prototype,{
  constructor:{
    value:Cat,
    enumerable:true,
    writeable:true,
    configurable:true
  }
})

const cat = new Cat("喵");
console.log(cat)
console.log(cat.say());

es6继承模式

class Animal{
  constructor(name){
    this.name = name
  }
  say(){
    console.log(this.name)
  }
}

class Cat extends Animal{
  constructor(name){
    super(name)
  }
}

const cat = new Cat("喵");
console.log(cat)
console.log(cat.say());

js继承方式很多,主要围绕this和prototype,大家有好的方式补充一下。

es6面向对象的写法很简单,没有c++,java的公有,保护,私有,以及c++可以多继承的写法。typescript可以有这种公有,保护,私有的写法。

es6转es5如下:

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

var Animal = /*#__PURE__*/function () {
  "use strict";

  function Animal(name) {
    _classCallCheck(this, Animal);

    this.name = name;
  }

  _createClass(Animal, [{
    key: "say",
    value: function say() {
      console.log(this.name);
    }
  }]);

  return Animal;
}();

var Cat = /*#__PURE__*/function (_Animal) {
  "use strict";

  _inherits(Cat, _Animal);

  var _super = _createSuper(Cat);

  function Cat(name) {
    _classCallCheck(this, Cat);

    return _super.call(this, name);
  }

  return _createClass(Cat);
}(Animal);