给定以下代码(StoriesMap.js)..。
// Initalization; Creates Map
var StoriesMap = function StoriesMap( id, location, tileset ) {
this.map = L.map( id ).setView([ location.lat, location.lon ], location.zoom);
// Add inital points to map
this.populate( location );
// Redraw on map movement
this.map.on("viewreset", function( event ) {
var location = {
lat: event.target._animateToCenter.lat,
lon: event.target._animateToCenter.lng,
zoom: event.target._animateToZoom
};
this.redraw( location );
});
var mapTiles = L.tileLayer( tileset.url, { attribution: tileset.attribution, minZoom: 4, maxZoom: 12 } ).addTo( this.map );
}
// Put some points on the map
StoriesMap.prototype.populate = function populate( location ) {
var priority = location.zoom - 3;
if ( typeof points === "object" ) {
var buffer = [];
for ( var i in points ) {
var point = points[i];
if ( point.priority <= priority ) {
var circle = L.circle([ point.lat, point.lon ], 100000, {
color: '#f03', fillColor: '#f03', fillOpacity: 0.5
}).addTo( this.map );
}
}
}
}
// Filters map contents
StoriesMap.prototype.filter = function filter( map, location ) {
console.log( "filter" );
}
// Redraws map points
StoriesMap.prototype.redraw = function redraw( map, location ) {
console.log ( this.map )
for ( var i in map._layers ) {
if ( map._layers[i]._path != undefined ) {
try {
map.removeLayer( map._layers[i] );
}
catch(e) {
console.log("problem with " + e + map._layers[i]);
}
}
}
}
StoriesMap.prototype.fake = function fake() {
console.log("Always Called when object is Initialized");
}
当我运行(从我的html):
var map = new Map();
我总是得到:
Always Called when object is Initialized
在我的控制台里。无论出于什么原因,我最后定义的原型都被视为构造函数,我不知道为什么。我不希望在初始化对象时运行该函数,是否假定它是构造函数?这种情况发生在我身上,我的正常反应是创建最后一个名为“假”的原型函数,并将其保留为空,但这个问题的正确解决方案是什么呢?
发布于 2013-11-07 11:49:24
这段代码在某个时候(可能是在某种构建过程或特定的过程中)与它连接在一起。另一段代码以带括号的语句开头:
StoriesMap.prototype.fake = function fake() {
console.log("Always Called when object is Initialized");
}
// start of other code...
(...);
但是,JavaScript将其理解为:
StoriesMap.prototype.fake = function fake() {
console.log("Always Called when object is Initialized");
}(...);
因此,StoriesMap.prototype.fake
并不等于该函数,而是使用带括号的表达式作为参数,立即调用该函数。StoriesMap.prototype.fake
被设置为立即调用的函数的返回值。
只需在函数表达式的末尾添加分号,就不会发生这种情况,因为括号内的语句和函数将用分号分隔:
StoriesMap.prototype.fake = function fake() {
console.log("Always Called when object is Initialized");
};
(...);
JavaScript的自动分号插入只有在缺少分号会导致违反语言语法的情况下才会发生。有关类似于此的示例,请参见ES 7.9.2的底部:
来源 A=b+c (d + e).print() 不通过自动分号插入来转换,因为开始第二行的带括号的表达式可以解释为函数调用的参数列表: A=b+ c(d + e).print() 在赋值语句必须以左括号开头的情况下,程序员最好在前面语句的末尾提供显式分号,而不是依赖自动分号插入。
https://stackoverflow.com/questions/19844376
复制相似问题