Javascript 错误';这';地图扩展中的参考
我试图在Javascript 错误';这';地图扩展中的参考,javascript,dictionary,typescript,map-function,Javascript,Dictionary,Typescript,Map Function,我试图在Map界面上编写一个简单的方法。这就是我迄今为止所做的: MapExtensions.ts: interface Map<K, V> { clone(): Map<K, V>; } Map.prototype.clone = () => { var self = this; console.log(self); let retval = new Map(); self.forEach((value,
Map
界面上编写一个简单的方法。这就是我迄今为止所做的:
MapExtensions.ts:
interface Map<K, V> {
clone(): Map<K, V>;
}
Map.prototype.clone = () => {
var self = this;
console.log(self);
let retval = new Map();
self.forEach((value, key) => {
retval.set(key, value);
});
//for (let [key, value] of self.entries()) {
// retval.set(key, value);
//}
return retval;
};
其他信息:
var _this = this;//It seems this is causing the problem.
Map.prototype.clone = function () {
var self = _this;
var retval = new Map();
console.log(self);
self.forEach(function (value, key) {
retval.set(key, value);
});
return retval;
};
如何成功执行此操作?这是因为您使用的是箭头函数。当需要访问此时,不要使用箭头功能
Map.prototype.clone = function() { ... }
非常感谢。这就解决了问题:)然而,我还是要等9分钟才能接受这个答案:)同时,你能解释一下,刚才发生了什么吗?当然。箭头函数只是将函数绑定到外部
this
值的语法糖。i、 e.箭头函数中this
的值是其父范围中this
的值。决不能对prototype
方法使用箭头函数。
Map.prototype.clone = function() { ... }