繁体   English   中英

我不了解原型的javascript部分

[英]I don't understand this part of the javascript by prototype

我目前正在使用使用cakephp和prototype.js的谷歌地图api V3。 我有一个JavaScript类,称为: TravelMapprManager ,它具有4个具有18个函数的类变量。

var TravelMapprManager = Class.create( {

  // id of container
    map_container : '',

  /* the current map */
    map : null,

  /* geocoding location */
    geocoder : null,

   /* user entered locations */
     user_journey : new Array(),

  //many other functions [.....]

initialize : function( map_container ) {

    this.map_container = map_container;

    // start the map
    Event.observe( window, 'load', this.displayMap.bind(this) );

    // observe the map buttons
    Event.observe( document, 'dom:loaded', this.initObservers.bind(this) );

},

   /*
    * Save the location entered
    */
findLocation : function() {

    location_name = $( 'LocationName' ).value;


    if ( location_name == '' ) {
        alert( "Please enter a location name." );
        return;            
    }

    // we only allow a maximum number of locations
    if ( this.user_journey.length >= 20 ) {
        alert( "Sorry! We have reached the maximum number of locations." );
        return;
    }

    // Do geocoding, find the longitude and latitude of the location
    if ( this.geocoder ) {

        var current_o = this;

        this.geocoder.getLatLng(
            location_name,
            function( point ) {

                if ( !point ) {
                    alert( location_name + " not found" );
                } else {

                    // store the location
                    current_o.storeLocation( location_name, point );

                    // center the location on the map and add push pin marker
                    current_o.map.setCenter( point, 13 );
                    var marker = new GMarker( point );
                    current_o.map.addOverlay( marker );
                }
            }
            );
        }
    }
})

var current_o = this;是什么? 函数中的位置是什么意思?

this内部函数findLocation与内部函数中的this关键字不同:

var current_o = this; //<-- Store reference to the `this` keyword inside the func
...
this.geocoder.getLatLng(
        location_name,
        function( point ) { //<------------ 
....

通过将this关键字存储在一个临时变量中,内部函数还可以访问this内部函数findLocation


一个简单的例子。 此代码将事件侦听器添加到下一个输入元素,同时保留对前一个元素的引用:

 var a = document.getElementsByTagName("input"); a[0].onclick = function(){ var firstElement = this; //First `this` a[1].onclick= function(){ firstElement.onclick = function(){}; //Reset this.onclick = function(){alert("This is different!")}; //Second `this` } } 

事件侦听器中的this关键字引用它们绑定到的元素。 在该示例中,第一个this引用元素input[0] ,而第二个this引用input[1] 当您不将第一个this存储在临时变量( firstElement )中时,您将无法引用前一个this (不能直接通过document.getElements..引用第一个元素)。

它是结合this局部变量,这样的对象可以传递给匿名函数内部使用getLatLng 这是必需的,因为在该函数内部this对象的引用可能不同-它取决于在getLatLng内部如何调用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM