7.7 class、extend编译

183 阅读1分钟

class编译

  • 创建Animal function
  • 通过Object.definePrototype给prototype添加属性
  • 静态属性添加到构造函数上

extend

  • Dog.prototype = Object.create(Animal)
  • 执行父类和自身构造方法
  • 添加自身的prototype属性
// 首先创建一个Animal类
class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; };
    move(distanceInMeters: number = 0) {
        console.log(`Animal moved ${distanceInMeters}m.`);
    }
}

// 子类Dog继承于Animal
class Dog extends Animal {
    age: number;
    constructor(name: string, age: number) { 
        super(name); 
        this.age = age;
    }
    bark() {
        console.log('Woof! Woof!');
    }
}

const dog = new Dog('wangwang', 12);
dog.bark();// 'Woof! Woof!'
dog.move(10);//`Animal moved 10m.`

编译后

// 第一部分
var __extends = (this && this.__extends) || (function () {
    return function (Dog, Animal) {
      // 修改d原型链指向
      extendStatics(d, b); 
      // 模拟原型链的继承
      function Temp() { this.constructor = d; }
        if(b === null){
              d.prototype = {}; // Object.create(null) 此时返回一个新的空对象{}
      } else {
            Temp.prototype = b.prototypevar temp = new Temp(); 
            // d.prototype.__proto__ = b.prototype
            // dog.__proto__.__proto__ = b.prototype
            d.prototype = temp;
      }
    };
})();

// 第二部分
// 首先创建一个Animal类
var Animal = /** @class */ (function () {
    function Animal(theName) {
        this.name = theName;
    }
    ;
    Animal.prototype.move = function (distanceInMeters) {
        if (distanceInMeters === void 0) { distanceInMeters = 0; }
        console.log("Animal moved ".concat(distanceInMeters, "m."));
    };
    return Animal;
}());

// 第三部分
// 子类Dog继承于Animal
var Dog = /** @class */ (function (_super) {
    __extends(Dog, _super);
    function Dog(name, age) {
        var _this = _super.call(this, name) || this;
        _this.age = age;
        return _this;
    }
    Dog.prototype.bark = function () {
        console.log('Woof! Woof!');
    };
    Dog.prototype.move = function (distanceInMeters) {
        if (distanceInMeters === void 0) { distanceInMeters = 5; }
        console.log("Dog moved ".concat(distanceInMeters, "m."));
    };
    return Dog;
}(Animal));

// 第四部分 无需解析
var dog = new Dog('wangwang', 12);
dog.bark(); // 'Woof! Woof!'
dog.move(10); // Dog moved 10m.

欢迎关注我的前端自检清单,我和你一起成长