Skip to content
On this page

继承

ts
class Person {
  maxage: number;
  name: any;
  obj: { name: string; };

  constructor(name: any) {
    const innerObj = {
      name: 'obj'
    }
    this.maxage = 100;
    this.name = name;
    this.obj = innerObj;
  }
  eat() {
    console.log('eat food')
  }
}


class Programmer extends Person {
  job: string;
  constructor(name: any) {
    super(name);
    this.job = 'coding'
  }
  coding() {
    console.log('coding world')
  }
}

被编译成:

js
var __extends = (function () {

    var extendStatics = Object.setPrototypeOf;


    return function (d, b) {

      extendStatics(d, b);

      function __() { 
        this.constructor = d; 
      } 

      d.prototype = ((__.prototype = b.prototype), new __()); 
    };
  })();

var Person =(function () {
  function Person(name) {
    var innerObj = {
      name: "obj",
    };
    this.maxage = 100;
    this.name = name;
    this.obj = innerObj;
  }
  Person.prototype.eat = function () {
    console.log("eat food");
  };
  return Person;
})();


var Programmer = (function (_super) {

  __extends(Programmer, _super);

  function Programmer(name) {
    var _this = _super.call(this, name) || this;
    _this.job = "coding";
    return _this;
  }

  Programmer.prototype.coding = function () {
    console.log("coding world");
  };
  return Programmer;
})(Person);



// true
let l2 =  Programmer.prototype.__proto__ == Person.prototype

let p = new Programmer;
p.eat()

可以简写为

js
function Programmer2(){}
function Person2(){}

Person2.prototype.age = 20
Programmer2.prototype =  new Person2();

let x = new Programmer2

let z =  x.age
z //20 

let l =  Programmer2.prototype.__proto__ == Person2.prototype
l // true
js
class A {}
class B extends A {}
let a = new A()
let b = new B()


B.proto === A
b.proto === B.prototype
a.proto === A.prototype
B.prototype.proto === A.prototype
b.proto.proto === A.prototype

Updated at: