javascript - 属性的类别属性

标签 javascript typescript class

我想要执行以下操作:

someProperty = myFunction().someFunction().someOtherFunction()

然而,最后一部分在不同的子类中被调用了很多次,所以我这样做了:

类别:

class Wheelies {
property0 = someFunction().someOtherFunction()

}

我想在子类中调用 getWheels,就像这样,但这不起作用:

class Car extends Wheelies {
property1 = myFunction().this.getwheels
}

请大家帮帮我,我的问题是我不知道为什么它不起作用,也不知道该怎么做。

最佳答案

这里有一个很好的解释 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

但基本上您需要返回 (this),以便可以链接函数调用。

class Wheelies {
    constructor(property1) {
        this.property1 = property1;
    }

    someFunction() {
    this.property1 = this.property1 + 'x'
    return this
    }

    someOtherFunction() {
    this.property1 = this.property1 + 'y'
    return this
    }
}


class Car extends Wheelies {
    // this inherits from Wheelies
}


const myCar = new Car("MyCar") 
console.log(myCar.property1) //"MyCar"
console.log(myCar.someFunction().property1) // "MyCarx"
console.log(myCar.someFunction().someOtherFunction().property1) // "MyCarxxy"

您还可以更改函数调用的顺序以产生不同的结果。

关于javascript - 属性的类别属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60165713/

相关文章:

javascript - 使用 d3-cloud 动态调整词云大小

javascript - 信号R ASP.NET

typescript - 如何使用带有等待语法的 typescript 获取 webdriverio 中的元素属性值?

c++ - 在库中定义数组大小而不为每次新使用修改它?

class - 对象初始化器 + 属性初始化器(从 C# 到 F#)

c++ - 尝试使用继承定义类时编译器出错

javascript - 将转义字符串传递给 JQuery($)-Function

javascript - 用正则表达式替换 jquery 中电话中的非电话符号

angular - 如何在 Visual Studio Code 中查看 JSCode 生成的文档?

javascript - 在 Create React App 中为节点模块添加自定义 Typescript 类型声明