我没有通过原型来理解javascript的这一部分

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

本文关键字:javascript 一部分 原型      更新时间:2023-09-26

我目前正在使用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 );
                }
            }
            );
        }
    }
})

在函数findLocation中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关键字存储在临时变量中,内部函数也可以访问findLocation内部函数this的属性。


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

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中如何调用。