【问题标题】:Typescript or JS class extensionTypescript 或 JS 类扩展
【发布时间】:2018-11-09 14:34:28
【问题描述】:

假设我想在我的游戏中使用 Warrior 课程。而我的战士只能行走。

class Warrior{

constructor(){}

walk(){
  alert ('I can walk!');
  }
}

x.walk(); //'I can walk!'
x.fight(); //error

然后我决定创建一个武器类,这样当这个类激活时,我在游戏中的战士就可以战斗了。一些我想象的伪代码:

class Weapon{

canFight(type:Warrior){
set warrior.fight=()=>{alert('I can fight!')};}

}

let x=new Warrior();

x.walk(); //'I can walk!'
x.fight() //'I can fight!'

因此,当出现某种神奇的扩展代码时,我需要使用新的方法和参数来扩展类本身及其所有实例。因此,我可以将行为封装在单独的类中,并将其扩展到其他类,而无需注意它们。

我看到的是 mixins,但其背后的想法是显式更改我的 Warrior 类以封装新功能。我不能说既然我的战士现在可以战斗了,我需要将我使用 Warriors 时的情况更改为某种新类型 - FighterWarriors,这样可以如果我需要用新行为快速增强对象,那将是一个真正的痛苦。

这是 c# 和 swift 中的工作技术,但我不了解其他语言。

所以问题是:如何在 Typescript 中做出这种行为?如果不能,纯JS是否支持这个?对于这个主题,我还能阅读什么?

【问题讨论】:

    标签: typescript extension-methods mixins


    【解决方案1】:

    您可以使用接口合并和模块扩充来将成员添加到类型。对于 JS 部分,事情非常简单,您只需要在 Warrior 原型上添加一个新属性

    // Warrior.ts
    export class Warrior {
    
        constructor() { }
    
        walk() {
            alert('I can walk!');
        }
    }
    // Weapon.ts
    import {Warrior } from './Warrior'
    
    export class Weapon{
        canFight(type:Warrior){
        }
    }
    
    declare module './Warrior' {
        interface Warrior {
            fight(): void
        }
    }
    Warrior.prototype.fight = function (this: Warrior){
        console.log("FIGHT");
    }
    
    // Usage.ts
    
    import {Warrior  } from './Warrior'
    import './Weapon'
    
    
    let x=new Warrior();
    x.fight();
    

    【讨论】:

    • 谢谢!一个问题,第二种情况是指Warrior.ts还是Weapon.ts?看来应该是武器.ts。
    • @gleb.kudr 是的,对不起,我的错
    猜你喜欢
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2016-12-02
    • 2020-10-08
    • 2018-01-03
    相关资源
    最近更新 更多