Dav*_*len 4 typescript typescript1.4
有没有办法覆盖打字稿中的[]操作?我们使用1.4,所以我们可以使用需要1.4的解决方案.
更新:我在最初的问题中非常不清楚.我的意思是我可以将其作为操作符添加到类中.在我的班上,我现在有一个方法:
public get(index : number) : LinkedListNode<t> {
if (this._first === null || (index >= this._count)) {
return null;
}
var node = this._first;
while (index-- > 0) {
node = node._next;
}
return node;
}
Run Code Online (Sandbox Code Playgroud)
我宁愿能够调用数据[5]而不是data.get(5).
有没有办法做到这一点?
感谢和抱歉这个令人难以置信的不准确的初始问题.
为了回应您对问题的更新,不能为一个类重载索引操作符 - 您无法data[5]代替data.get(5).
在我看来,之所以没有实现,是因为JavaScript允许使用括号访问对象的属性,这会产生一些歧义.例如,如果data.myProperty是一个存在并被data['myProperty']调用的属性,则很难确定它是否应该返回该myProperty属性,或者是否应该将字符串'myProperty'传递给索引重载.
无法更改结果:
var a = [];
Run Code Online (Sandbox Code Playgroud)
想象一下如果允许人们改变这种行为可能会出现的问题?库A可以通过一种方式定义它,然后库B可以用自己的行为覆盖它...意味着库B现在使用库A的[]行为.
你可以做的是为Array原型添加方法:
interface Array {
log: () => void;
}
Array.prototype.log = function() {
console.log(JSON.stringify(this));
};
Run Code Online (Sandbox Code Playgroud)
然后使用:
var a = [];
a.log();
Run Code Online (Sandbox Code Playgroud)
但是,非常不推荐这样做!您不应该修改您不拥有的对象,因为它可能导致无法预料的问题.不这样做的原因类似于为什么改变[]行为会导致问题:
log方法.log一种不同的方法.log,库A 的方法将无法正常工作,因为它使用了库B的方法.建议
我建议你创建自己的数组实现:
class MyArray<T> implements Array<T> {
private _underlyingArray : Array<T> = [];
// implement methods for Array here
log() {
console.log(JSON.stringify(this._underlyingArray));
}
}
Run Code Online (Sandbox Code Playgroud)
或者创建一个帮助类:
class ArrayHelper {
static log<T>(a: Array<T>) {
console.log(JSON.stringify(a));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4515 次 |
| 最近记录: |