1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are an angel..:) I read about bind for some reason I am not understanding the java-script terminology regardless of how much I read..Thank you very much...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.