当我尝试在TypeScript中创建继承时,将生成以下JavaScript:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
看起来与应该生成的完全一样。但是问题在于,Firefox在执行时会显示以下消息:
TypeError: b is undefined
在Chrome中,错误看起来有些不同,但似乎是由同一原因引起的:
Uncaught TypeError: Cannot read property 'prototype' of undefined
在打字稿中的实现看起来像这样
class Movie extends Medium {
//Some Fields
constructor(title: string, description: string, ageRestriction: AgeRestriction, isBluRay: boolean) {
super(title, description, ageRestriction);
this.isBluRay = isBluRay;
}
}
class Medium implements IMedium {
//Getters, Setters and Fields
constructor(title: string, description: string, ageRestriction: AgeRestriction) {
this.title = title;
this.description = description;
this.ageRestriction = ageRestriction;
}
}
我已经尝试了各种编译代码的方法,但是结果总是一样的
要摆脱错误,您必须将Medium
类声明放在之一之前Movie
。
请注意,生成的js代码不仅是函数定义。它是函数和变量。这一切都与众不同。因为您同时具有声明和表达式。关于此问题的更多信息以及为什么以js顺序表达表达式很重要,您可以在此出色的文章中阅读:JavaScript函数声明和评估顺序
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句