0

给定以下代码(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

在我的控制台中。无论出于何种原因,我最后定义的原型被视为构造函数,我不确定为什么。我不希望在初始化对象时运行该函数,是否假定它是构造函数?这种情况以前发生在我身上,我的正常反应是创建一个名为“fake”的最后一个原型函数并将其留空,但这个问题的正确解决方案是什么?

4

1 回答 1

2

此代码在某些时候(可能在某种构建过程或缩小过程中)连接了其他代码。其他代码以带括号的语句开头:

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()

在赋值语句必须以左括号开头的情况下,程序员最好在前面的语句末尾提供一个明确的分号,而不是依赖于自动分号插入。

于 2013-11-07T19:49:24.827 回答