我想要执行以下操作:
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/