The parentheses at the end of javascript object [duplicate] - javascript

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
`new function()` with lower case "f" in JavaScript
(3 answers)
Closed 8 years ago.
var ajaxCall = new function () {
var baseUrl = 'Home/',
getCategory = function (callBack) {
$.getJSON(baseUrl + "GetCategories", function (data) {
callBack(data);
});
}
getSubCategory = function (callBack) {
$.getJSON(baseUrl + "GetSubCategories", function (data) {
});
}
return {
getCategory: getCategory,
getSubCategory: getSubCategory
};
}();
This is a part of our front end code. I know that we are creating an object with functions and this renders flexibility.
I wonder two things:
1. the new keyword - why not just leave it like var ajaxCall = function(){}; ??
2. The () at the end of this code snippet, we do we need that?
ANY comments to newbie here is welcome. Thanks.

Related

How I can return a string from a javascript callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.

How to extend the scope of a function variable in javascript? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 6 years ago.
I have a basic function in protractor written as :
this.getCurrentUrl = function () {
browser.getCurrentUrl().then(function(url){
console.log('url : '+url);
});
};
Now is there a way I can access the 'url' outside of the inner function scope, because I need to return this value to some other function calling this one. I need to get the value and return it from outside of then(function(url){...}
the url will be acquired async, so you can't just assign it. You probably want to hand it a callback.
function handleUrl(url) {
// here is where you do something with the url
}
// let your callback be called
this.getCurrentUrl = function(fn) {
browser.getCurrentUrl().then( function (url) {
fn(url);
})
}
// make the call with your handler
this.getCurrentUrl(handleUrl);
Another approach is to have your function return a "container" and that gets inflated later. Then later you can check your container. Since the behavior is async, you won't know when it will be ready, so you can check for it on an interval or something...
// return a container object
this.getCurrentUrl = function() {
var urlContainer = {};
browser.getCurrentUrl().then( function (url) {
urlContainer.url = url;
});
return urlContainer;
}
var urlContainer = this.getCurrentUrl(); // starts off as an empty object
urlContainer.url // undefined
// then shortly in the future
urlContainer.url // has some url
Yet a third way is to return a closure
this.getCurrentUrl = function() {
var urlValue;
browser.getCurrentUrl().then(function(url) {
urlValue = url;
});
return function() {
return urlValue;
}
}
var getUrl = this.getCurrentUrl();
getUrl(); // initially, returns undefined;
// keep trying. then shortly in the future...
getUrl(); // now has the url

Given a function in a string format how do i convert it back to a function in javascript? [duplicate]

This question already has answers here:
Given a string describing a Javascript function, convert it to a Javascript function
(8 answers)
Closed 7 years ago.
Say I have a function in javascript
var fn = function () {
return 6 + 5;
};
and then I do
fn.toString();
which returns
"function () { return 6 + 5; }"
how can I turn this back into a function and eventually call it later on. I've tried eval as other people have said but this does not seem to be working for me. Any help would be much appreciated!!!
You can give a name to the function, then you can call it. This should work
var fn = function () {
return 6 + 5;
};
var stringFunc = fn.toString();
eval("var newfn = " + stringFunc);
console.log(newfn())
you can also execute it passing the parameters like this
console.log(eval("("+stringFunc+")()"))
#LeeDennis just call fn(); instead of fn.toString(); the variable "fn" is the function you just need to add the parenthesis.
I console logged the outputs so you can see them.
//CODE
<!DOCTYPE html>
<html>
<head>
<script>
var fn = function () {
return 6 + 5;
};
console.log(fn()); //returns 11
console.log(fn.toString()); //returns "function () { return 6 + 5; }"
</script>
</head>
<body>
</body>
</html>
Use eval():
fnString = 'function () { return 6 + 5; }';
fn = eval('(' + fnString + ')');
alert(fn());
Check this out:
JavaScript eval() "syntax error" on parsing a function string

Access this in prototype function after a callback [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I have following code :
function A() {
this.value = 'a_value';
}
A.prototype.getValue = function(){
console.log(this.value); // got undefined, expected 'a_value'
}
setTimeout(new A().getValue, 100);
why i get this.value as undefined.?
and how how do i access this.value?
EDIT : i am not allowed to change the setTimeout line (last line) of code.
Hint: have you tried console.log(this);?
You are only passing the getValue function to setTimeout, not its context. Something like this would work: setTimeout(function() {new A().getValue();},100); But without changing that last line, there's basically nothing you can do.
you can avoid using the this altogether and not having this kind of problems with the following technique :
var A = function () { // no new no this
var value = 'a_value';
var getValue = function(){
console.log(value);
};
return Object.freeze({
getValue ,
});
};
setTimeout(A().getValue, 100);
or write
var a = new A();
before, and then
setTimeout(a.getValue.bind(a), 100);

Run callback saved in variable on click [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I have an object containing a number of buttons (label and callback) which I dynamically want to add to the DOM:
var buttons = {
'Save': function() {
return false;
},
'Abort': function() {}
};
for(label in buttons) {
$('#buttonbar').append('<button>' + label + '</button>');
var callback = buttons[label];
$('#buttonbar button:last-child').click(function() {
//var result = callback();
alert(callback);
});
}
But regardless which button I click, the variable callback always contains the function of the last button. See this fiddle.
Any ideas how to solve that?
Thanks to the hint given by Barmar I found the solution:
var buttons = {
'Save': function() {
return false;
},
'Abort': function() {}
};
for(label in buttons) {
$('#buttonbar').append('<button>' + label + '</button>');
var callback = buttons[label];
(function(cb) {
$('#buttonbar button:last-child').click(function() {
alert(cb);
});
})(callback);
}

Categories