【问题标题】:How to inherit from existing AMD js class in TypeScript compilng to AMD module?如何从 TypeScript 编译中的现有 AND js 类继承到 AMD 模块?
【发布时间】:2015-04-06 14:10:57
【问题描述】:

我确实尝试了以下方法:

class Child {
    public func() {
       alert("hello");
    }
    constructor() {
        Parent.apply(this, arguments);
    }
}
Child["prototype"] = Object.create(Parent.prototype)
Child["prototype"].constructor = Child;

但是 Child 类的实例没有 func() 方法。

js类如何继承?

【问题讨论】:

    标签: javascript oop inheritance typescript


    【解决方案1】:

    一般情况

    只需使用declare 来声明现有类。

    declare class Parent { // produces no JS code
        constructor(val);
    }
    class Child extends Parent {
        constructor(val) {
            super(val);
        }
    }
    

    外置模块(AMD)案例

    必须在定义文件.d.ts 中描述外部模块。

    文件ContainerSurface.d.ts

    declare class ContainerSurface {
      constructor(options);
    }
    export = ContainerSurface;
    

    使用方法:

    import ContainerSurface = require('ContainerSurface');
    
    class Child extends ContainerSurface {
      constructor(options) {
        super(options);
      }
    }
    

    【讨论】:

    • 如果这行得通,那就太好了!但是我收到以下错误:Extended 导出类“Child”的子句已经或正在使用私有名称“Parent”。任何想法如何告诉编译器 Parent 只是一个非私有的全局变量?
    • 我正在尝试扩展 AMD 模块 raw.githubusercontent.com/Famous/famous/develop/src/surfaces/…。而且我的 Child 类也编译了生成 AMD 模块的选项。如果我将您的示例粘贴到 typescriptlang.org 游乐场,它可以工作,但无法在那里启用 AMD 编译。如果我编译您的代码,并说编译到 AMD 模块,如果我添加 export=Child; 则会给出错误;在文件末尾。
    • AMD 将文件 ContainerSurface.js 添加到 require 列表中,但是文件没有编译成实际需要的代码,这不起作用:-(
    • :( 可能我错过了什么。我没有使用 AMD 的经验。但是,我的示例使用参数 --module amd 编译。实际需要的 JS 代码是什么?
    • 你是对的!有用!我必须在 .d.ts 文件的导入语句中添加路径,以便它模仿 require(AMD 版本)从中加载实际 AMD 模块的真实路径。我在我的源文件夹中介绍了结构,即着名/surfaces/ContainerSurface.d.ts.
    猜你喜欢
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多