简体   繁体   中英

Function scope error in javascript

I have a code and it does as follows

var Device = function(temp){
    this.list = temp;

    Device.prototype.getList = function(){
        return list;
    };

    Device.prototype.foo = function(tempFunc){
       navigator.geolocation.watchPosition( 
    function(pos) {
                //I want to call getList here so lets do it
                //Method No1 
                var list = this.getList();
                //Method No2
                var list = Device.prototype.getList();
                //Method No3
                var list = getList.call(Device)
            },
            funciton(){
              console.log("Error")
            }                         
    };
};

In all three methods I am getting an error. 1.object [object global] has no method called get list. 2. list is undefined 3. Can not call a undefined.

I also tried to call the foo method in this context then pos is not recognized in the context and passing the getList as a argument did not help me either. I think I do have understanding of the issue here but I do not know how to handle it. I need the getList method to be called in the anonymous function but that function gets called in the global context is my thinking. Could anyone sort this out for me.

First, it's generally not a good idea to build prototype properties inside a constructor function.

function Device(temp) {
  this.list = temp;
}

Your "getList" function has to explicitly retrieve the "list" property of the receiver object (the value of this ):

Device.prototype.getList = function() {
  return this.list;
}

The most complicated part is setting up the callback function, but luckily it's not bad:

Device.prototype.foo = function(tempFunc){
   navigator.geolocation.watchPosition( 
       function(pos) {
         var list = this.getList();
         // ... whatever ...
       }.bind(this), // <-- the important part
       function(){
         console.log("Error")
       }
    );                     
 };

The .bind() function will give you a function that's got this pre-arranged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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