例如
order(money: number) {
if (money >= this.drinkPrice && this.quantity > 0) {
this.setQuantity(this.quantity - 1);
this.setChange(money - this.drinkPrice);
alert(this.quantity);
} else {
alert(this.quantity);
}
}
render(item: Drink, container: HTMLUListElement, money: number) {
const li = document.createElement('li');
const h4 = document.createElement('h4');
h4.innerText = `${item.drinkName} ${item.drinkPrice} ${item.quantity}`;
li.append(h4);
const btn = document.createElement('BUTTON');
btn.id = this.drinkName;
btn.innerText = this.drinkName;
btn.addEventListener('click', item.order());
li.append(btn);
container.append(li);
}
现在在另一个我写的文件中:
const money = document.querySelector('input') as HTMLInputElement;
const container = document.querySelector('ul') as HTMLUListElement;
const espresso = new Espresso('Espresso', 60, 15);
const cappuccino = new Cappuccino('Capuccino', 120, 20);
espresso.render(espresso, container, money.valueAsNumber);
cappuccino.render(cappuccino, container, money.valueAsNumber);
您会看到我将open class TestClass
fun TestClass.testFunc(): String = "ext"
重命名为import xx.xx.testFunc as rename
class OverTestClass : TestClass() {
fun testFunc(): String {
return "OverTestClass - " + rename()
}
}
,因此我可以在TestClass.testFunc()
中呼叫rename()
。但这并不酷,我想要的方式是这样的:
TestClass.testFunc()
有可能吗?
我知道这个问题是颠倒的,我想要这样做的原因是:我正在编写同时在java和kotlin中使用的lib,我不想这样编写Java:
OverTestClass
我要:
return "OverTestClass - " + super.testFunc()
因此,我将XxxKt.func(obj)
作为实例函数。并直接通过其“超级”扩展功能实现
答案 0 :(得分:2)
我会尝试向上广播到TestClass:
class OverTestClass : TestClass() {
fun testFunc(): String {
return "OverTestClass - " + (this as TestClass).testFunc()
}
}