I am trying to achieve something like the following but dont know whats wrong:
$.a = function() {
// some logic here
function abc(id) {
alert('test'+id);
}
}
$.a.abc('1');
I tried using the return function, but that doesnt seem to work either. Can someone please help.
Thank you for your time.
Since $.a must be a function in itself, you'll have to add the abc function as a property to the $.a function:
$.a = function () {
// some logic here...
};
$.a.abc = function (id) {
alert('test' + id);
};
If abc must be defined from within the $.a function, you can do the following. Do note that $.a.abc will not be available until $.a has been called when using this method! Nothing inside a function is evaluated until a function is called.
$.a = function () {
// Do some logic here...
// Add abc as a property to the currently calling function ($.a)
arguments.callee.abc = function (id) {
alert('test' + id);
};
};
$.a();
$.a.abc('1');
$.a = (function(){
var a = function() {
//...
};
a.abc = function() {
//...
}
return a;
})();
Related
I have a (asynchronous) function that gets the ID of a logged in user in Chrome. I'm trying to return the value of the ID with a callback but it keeps returning 'undefined'.
Before someone tries to mark this a duplicate, I used the code from here (and tried other places too): How to return value from an asynchronous callback function? But it didn't work:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
callback(userInfo.id);
});
}
getGaia(function(id){
return id;
});
var gaiaId = getGaia();
I get the following error:
'callback' is a not a function
What exactly am I doing wrong / what is the correct code?
That is because you are not providing a callback.
function doSomethingLater(callback) {
setTimeout(callback, 1000);
}
console.log('This is before the callback');
doSomethingLater(function() {
console.log('This is the callback')
});
So when you are calling var gaiaId = getGaia(); you are not passing in a callback function
[Edit] This is what your code would need to look like:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
// This will call the function that you pass in below
//and pass in userInfo.if as a parameter
callback(userInfo.id);
});
}
var gaiaId = getGaia(function (id) {
// id === userInfo.id from above
// Do something with the id that you pass in
});
You can think of functions like variables in JavaScript,
So you can assign a function to a variable like this:
var foo = function () { ... }
This means that you can pass this into functions like normal variables. When you pass the function in as a parameter, you are assigning the function to the name that you specify in the parameters:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
All I have done above is, instead of creating the variable foo I just created the function inline:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
// Becomes:
function hasCallback(callback) {
callback(); // Using the function that you passed in
}
hasCallback(function () { ... });
So I have a function like
func()
{
const curVal = this.curVal;
const callAgain = () => { func(); };
Axios.get('somecontroller/someaction')
.then(response =>
{
const newVal = response.data.curVal;
if(curVal === newVal)
setTimeout(callAgain, 500);
else
// ....
})
.catch(response =>
{
// ...
});
}
and my browser is complaining about the line
const callAgain = () => { func(); };
saying that func is undefined. Any idea why? How can I fix?
You cannot define a function the way you posted.
However, you can for example use the function keyword to define your function:
function func() {
...
}
func(); // it works!
Edit:
According to your comment, this is a object method declaration. In order to make this work, you first need to make sure your browser supports this particular ES2015 feature or if not, you transpile it to valid ES5.
Then you should be able to access the function using this.func():
const callAgain = () => { this.func(); };
In case you are using func() e.g. as a callback for a DOM event, you also have to make sure that this is bound correctly in func, for example by explicitly binding it in the constructor:
constructor() {
...
this.func = this.func.bind(this);
}
Define the function using either of the following:
function func(){ ... }
Or...
var func = function(){ ... }
When you define it like this:
func() { ... }
JavaScript thinks you're trying to execute an existing function called func, and then run the block of code { ... }
I presume it is possible to create a JavaScript function that disables it self after it is done running.
Is possible? How can this effect be achieved?
Wrap arbitrary runnable in following manner:
function once(subject) {
var first = true;
return function() {
if (first) {
first = false;
return subject();
} else {
return null;
}
};
}
var wrapper = once(function() {alert("No more!");});
wrapper(); // alerts
wrapper(); // noop
Runnable will only be executed on first invocation of wrapper.
You can convert a function of arbitrary arguments to an argumentless runnable.
If you want the functionality to be happen only once you can use the following function
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
Courtesy: https://davidwalsh.name/essential-javascript-functions
something like this?
function a(){ alert(1); a = null;}
invoke a() once, second time it will say
Uncaught TypeError: a is not a function
if the function is anonymous, then make it IIFE
(function(){ alert(1);})();
var _flag = true; // Have a flag variable.
function oneTimer(){
// Check flag is set to true or not
if(!_flag) return;
_flag = false;
// Your function definition here.
}
As commented, if you want to execute a function only once, you should try IIFE. These functions are invoked immediately and cannot be called afterwards.
Following is a sample code.
(function test() {
console.log("test");
(function innerFunc() {
console.log("Inner Function");
})();
try {
innerFunc();
} catch (ex) {
console.log(ex)
}
})();
try {
test();
} catch (ex) {
console.log(ex)
}
Pretty easy, just assign an empty function to the function:
function once() {
alert('once');
once = function () { };
}
once();
once();
I have a very common question about javascript
i have a globally declared variable but how can a function with that variable pass the value in the globally declared variable then use it in the second function??
var ID;
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
alert(ID);
}
})
}
function test1() {
$.getJSON("/TestSite?Test=" + ID; )
}
alert(ID);
test();
test1();
Function test alert the ID but when i declare it Globally it was undeclared.
Can someone help me with this??
Thanks
I think you are expecting getJSON to be synchronous, but it is not. If the calls are dependent you should nest them:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
ID = this["ID"]
$.getJSON("/TestSite?Test=" + ID; )
})
})
}
test1 is being called before test has completed its getJSON call
Because getJSON is asynchronous, the proper way do perform what you need is to use the returned ID in the callback of getJSON:
function test() {
$.getJSON('/Test1/GetTestID', function (test) {
$.each(test, function () {
var theId = this["ID"];
alert(theId);
test1(theId);
}
});
}
function test1(id) {
$.getJSON("/TestSite?Test=" + id);
}
test();
Try this first you set you id to Zero
var ID =0;
I have a function like this:
retrieveData();
and then javascript code like this:
var retrieveData = function ()
{
function () { $('#updater').show(); }
$.post('......
This is I think a simple question but how can I pass an argument to the retrieveData function and have it availabe for use in the code following the .post ?
Simply
var retrieveData = function (a) {
$.post(...);
// use `a` here
}
retrieveData("some value");
var retrieveData = function (answer) {
$.post('The answer is ' + answer);
}
retrieveData(42);