Java script call by reference - javascript

I have to call setTimeout() with parameter grpname,but initially it has not been declared but i want it to refer to the same value if change afterwords...
function test(grpname) {
$('.middle').load("display.php", {
"grpname": grpname
});
}
$(document).ready(function (e) {
$('#inv').hide("fast");
$('#t2').hide("fast");
$('#username').click(function () {
document.userid.username.value = "";
});
var grpname = document.userid.grpname.value;
$('#signup').click(function () {
$('#username').focus();
});
$('#signin').click(function () {
var username = document.userid.username.value;
setTimeout(test.bind(null, grpname), 1000);
....
}

In JavaScript, primitive parameters are passed by value and object parameters are passed by reference. (https://snook.ca/archives/javascript/javascript_pass)
Observe this fiddle: https://jsfiddle.net/8hkmysr1/8/
When the callback function runs, param1 is unaffected by the change to the global value, as it was passed by value. param2 is affected as it was passed by reference.
So you must either pass an object to the function so that the closure references the original object, or you must declare the variable in the global scope and read that value.

Related

Why is "this" pointing to the "window Object" in the callback function?

var callBackFunc = {
value : "CallBackValue",
getValue : function(callback) {
callback();
}
}
var TestingFunc = {
value : "TestingValue",
alertValue : function() {
console.log(this);
}
}
$(function() {
callBackFunc.getValue(TestingFunc.alertValue);
});
I don't want answers to be able to use it properly, but I wonder why "this" points to Window Objects. Plz... Help me!!
because arguments passed by value which means
callBackFunc.getValue(TestingFunc.alertValue);
equals to
callBackFunc.getValue(function() {
console.log(this);
});
so ,callback() works
(function() {
console.log(this);
})()
so ,you get window.
If arguments passed by name ,in this case name is TestingFunc.alertValue,then you will get what you want like :
callback() equals to TestingFunc.alertValue()
However,js works by value not name
The plain callback function reference is passed as a parameter to the callBackFunc.getValue, so there is no current this context will be formed with the plain function and the default this leads to the global object (window).
In order to form the context, we can use call, bind, apply methods.

function inside function with same name in javascript

If I pass function to a function with same function name and handler name, which one will get precedence ? and how to access each of those two inside function in case in need to do recursion as well as refer to the passed function. See below code.
var f1,f2;
(function f(f){
return typeof f(f2); /*please check below comments for output of this line*/
})(function(f1){ return 1; });
/* this will call the passed function,why not recursion will not happen here? */
The function parameter gets precedence over the function's own name. If you shadow or overwrite a variable, you can't access it (unless it's a shadowed global).
Solution is to use different names.
The recursion doesn't happen simply because the argument of the function get precendence than the function itself. here is an example that shows it:
(function f (f) {
return f.name;
}) (function funcName () { }); // this will return funcName
if we change the name of the argument to f1, f will become the reference of the function itself
(function f (f1) {
return f.name;
}) (function funcName () { }); // this will return f
I see that you use jquery. So I want to ask where do you have declared your functions? inside
<script type="text/javascript">
$(document).ready(function(){
function f(){
return 'this is local function inside anonymous function, so it's invisible for recursion in aside of current document ready'
}
});
//or here?
function f(){
return 'this function is a window object property, and must be visible for recursion';
}
</script>

Why the global variable remain the same after calling a function to increase it?

Why the global variable is still 5 after calling the increment function? Thanks in advance for any help.
<script>
function increment(val) {
val+=1;
}
var val = 5;
increment(val);
alert(val);
</script>
function increment(val) {
val+=1;
}
declares a variable val local to your function. You change your local variable and not the external one. It's the same as
function increment(val2) {
val2+=1;
}
You could do this :
function increment(val) {
return val+1;
}
var val=5;
val = increment(val);
or
function increment(holder, varname) {
holder[varname] = holder[varname]+1;
}
var val=5;
increment(window, 'val');
This is because primitive variables in Javascript are passed by value, not by reference.
When passing in a primitive type variable like a string or a number,
the value is passed in by value. This means that any changes to that
variable while in the function are completely separate from anything
that happens outside the function
Check this great blog entry for more info on this subject:
http://snook.ca/archives/javascript/javascript_pass
You don't need to pass the global vars.
When you pass the argument to a function, its creating a local copy of the valriable. So if you want to effect the global variable from the function, you don't pass it when calling the function, because you can anyway access the global variable, without passing.
<script>
function increment() {
val+=1;
}
var val = 5;
increment();
alert(val);
Notice that when you are defining the increment() function you have specified the parameter as **val**. So inside the function every reference to val is for this local argument. If you want to access the actuall global variable use window.val.

getting the "this" that a function's caller was called with in JavaScript

Is it possible to get the this that a function's caller was called with in JavaScript without passing this to the arguments in a way which supports IE as well as Firefox/Chrome et al?
For example:
var ob = {
callme: function() {
doSomething();
}
}
ob.callme();
function doSomething() {
alert(doSomething.caller.this === ob); // how can I find the `this` that
// `callme` was called with
// (`ob` in this case) without
// passing `this` to `doSomething`?
}
I'm starting to suspect it's not, but I thought I may as well ask as it'd make my code much shorter and easier to read.
Well, the closest I can think, without technically passing the value as an argument, would be to set the this value of the doSomething function.
Since the doSomething function is not bound to any object, by default, if you call it like doSomething(); the this value inside it will refer to the Global object, and that's normally not too useful...
For example:
var ob = {
callme: function () {
doSomething.call(this); // bind the `this` value of `doSomething`
}
};
function doSomething () {
alert(this === ob); // use the bound `this` value
}
ob.callme();

Passing variable with JavaScript function

I am trying to pass variable though the GetDetail function below. I can pass string/number and it works properly.
But I'm unable to pass variable
detLink.onclick = new Function ("GetDetails()");
detLink.setAttribute('onclick',"javascript:GetDetails()")
detLink.onclick = function () { GetDetails ( parameter1, parameter2, ... ); }
which is an anonymous function.
Read also The function expression (function operator)
A function expression is similar to and has the same syntax as a function declaration
function [name]([param] [, param] [..., param]) {
statements
}
name
The function name. Can be omitted, in which case the function becomes
known as an anonymous function.
param
The name of an argument to be passed to the function. A function can
have up to 255 arguments.
statements
The statements which comprise the body of the function.
detLink.setAttribute('onclick',"javascript:GetDetails("+yourVariableName+")")
When You set attribute You are using string datatype, thus you have to stitch function name with variable VALUE
If you have access to the variable in question when you set the click handler,
detLink.onclick = function() {
GetDetails(foo);
}
If you don't,
detLink.id = uniqueId;
detLink.onclick = function() {
var foo = globalData[this.id];
GetDetails(foo);
}
// somewhere else in your code, where you know the value of the variable
globalData[detLink.id] = foo;
var val1 = "Hell world"
detLink.onclick = GetDetails( val1 );
function GetDetails( myVar ){
alert ( myVar );
}

Categories