Can I access the function arguments outside the function?
Here is my code:
function viewmessage(username,name) {
//alert(name + " : " + username);
$('#heading').html(name);
$.get('/notification/viewmessage', {user:username}, function(data) {
$('#messagesfrom').html(data);
$('#newmessage').slideDown(200);
});
}
alert(name + " : " + username);
How do you call a variable inside a function in JavaScript? So the easiest way to make your variable accessible from outside the function is to first declare outside the function, then use it inside the function. var a; Parse.
var camera = (function () { function a(){ console. log('calling ..a'); } function b(){ console. log('calling .. b'); } })(); //calling function a() from outside camera.
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0 . You can use arguments.
You can't, unless you declare the variable outside the function.
You can only use the same variable names in the global scope:
function viewmessage(username, name){
window.username = username;
window.name = name;
}
alert(window.name + " : " + window.username ); // "undefined : undefined"
alert(name+" : "+username); // ReferenceError: 'name' not defined
In a local scope, you have to use variable names which are re-declared inside the function:
var username2, name2;
function viewmessage(username, name){
username2 = username; // No "var"!!
name2 = name;
}
alert(username2 + " : " + name2); // "undefined : undefined"
viewmessage('test', 'test2');
alert(username2 + " : " + name2); // "test : test2"
You can use RegEx (regular expressions) to get the arguments:
function viewmessage(username, name) {/*...*/}
var args = viewmessage.toSource()
.match(/\((?:.+(?=\s*\))|)/)[0]
.slice(1).split(/\s*,\s*/g);
//args = ["username", "name"]
Make sure though, you don't have any spaces after the (
or before the )
. Otherwise, you might have this result:
function viewmessage( username, name ) {/*...*/}
var args = viewmessage.toSource()
.match(/\((?:.+(?=\s*\))|)/)[0]
.slice(1).split(/\s*,\s*/g);
//args = [" username", "name "]
Or you use trim()
on each of the arguments after you gathered them:
args.forEach(function (e, i, a) {a[i] = e.trim();});
//args = ["username", "name"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With