您可以通过 including a mixin 更改 Leaflet.js 类的行为.
教程Extending Leaflet: Class Theory说:
If a class is already defined, existing properties/methods can be redefined, or new ones can be added by using .include():
但是,当尝试执行此操作时,我收到了一个超出最大调用堆栈大小
错误。
var DemoClass = L.Class.extend({
value: 42,
demoMethod: function() {
return this.value;
}
});
DemoClass.include({
demoMethod: function() {
return DemoClass.prototype.demoMethod.call(this) * 2;
},
secondMethod: function() {
return this.value;
}
});
var instance = new DemoClass();
console.log("value=" + instance.value);
console.log("secondMethod()=" + instance.secondMethod());
console.log("demoMethod()=" + instance.demoMethod()); // gives a call stack exceeded
<script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>
如果相关,则实际代码将覆盖 L.Marker.onAdd()
。
最佳答案
demoMethod: function() {
return DemoClass.prototype.demoMethod.call(this) * 2;
},
你正在进行无限递归调用,就在那里。
JS 有时很奇怪,这一次就是其中之一。通过引用 DemoClass.prototype
,您指的是 DemoClass.prototype
的最新状态...所以 DemoClass.prototype。 demoMethod
指的是自身。
每当您覆盖原型(prototype)方法或属性时,前一个方法或属性会得到 de-referenced and potentially garbage-collected .
如果要引用之前定义的方法,必须保留对之前定义的方法的引用。
这通常需要一些 JS closure 形式的技巧(在某些受控变量范围内保留对原始值的引用)。有多种方法可以做到这一点:将对先前原型(prototype)的引用作为类属性保留,就像@Jaws 所做的那样;在某处关闭;做一个 IIFE就像在Leaflet.GridLayer.FadeOut ,或任何可以让您保留对原始方法定义的引用的内容。
关于javascript - 通过 include() 更改 Leaflet 类的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40604970/