1

Today I saw navigator.geolocation.getCurrentPosition(function(obj){console.log(obj)}) code. In this code getCurrentPosition method return geoposition object as a parameter if you passed function in that method. I wonder how it is worked. If I have a method which return string and I want it to be return like the way that getCurrentPosition do, How can I achieve that. for example

var me={
fn:function(){    
return "getObj";    
}    
}

me.fn(function(obj){console.log(obj)})  should be print //"getObj"
Jitender
  • 7,593
  • 30
  • 104
  • 210

2 Answers2

3

You need to pass a callback function:

var me = {
    fn: function(callback)
    {
       callback("getObj");
    }
};

me.fn(function(obj) { console.log(obj); });
haim770
  • 48,394
  • 7
  • 105
  • 133
  • is callback predefined function in javascript? – Jitender Jan 05 '15 at 18:30
  • @amit, No. You can name it `foo` or anything you want, it's just the parameter name. Though it's recommended to check whether it's actually a function using `if (typeof callback === 'function')`. – haim770 Jan 05 '15 at 18:31
1

In this code getCurrentPosition method return geoposition object as a parameter if you passed function in that method.

It doesn't return the information as a parameter. It calls the function you give it with the information as an argument (we use the word "argument" in JavaScript, not parameter). Functions are first-class objects in JavaScript, you can pass references to them into functions and use them within the functions.

So if you have a foo function and want it to call a callback with its result:

function foo(callback) {
    // ...come up with the result, then:
    callback(result);
}

This is particularly useful for functions that will either A) Call the callback repeatedly (like Array#sort does), or B) Cll the callback asynchronously (like geolocation does).

Example:

function giveMeARandom(min, max, callback) {
  callback(min + Math.floor(Math.random() * (max - min)));
}
giveMeARandom(1, 10, function(value) {
  snippet.log("Value is " + value);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875