Jump to content

Call Javascript Function By Reference


Ajmal

Recommended Posts

incorrect,this will only create a javascript error because b() isn't a function,look at the following correct code

function a(){return confirm("test")}var b = a()document.write(b)

the output will be true or falsean object like b can't become a function by using b = a() ,it will only set the value of b and will not make b a function

Link to comment
Share on other sites

an object like b can't become a function by using b = a() ,it will only set the value of b and will not make b a function
Yes, but only because you executed function a(). Synook didn't do that. He assigned object b a reference to object a, not the return value of object a.It's a simple enough matter to paste Synook's code into your Firefox Error Console and test it. Or consider this obvious example, which illustrates assignment by reference as it is done in maybe 10 million scripts:
function func() {	alert("test");}document.getElementById("my_button").onclick = func;

This will also work:

function first(reference) {	 reference(); }function second() {	 alert("test"); }var third = function () {	first (second);};third();

If that's not passing by reference, I don't know what is. :)

Link to comment
Share on other sites

incorrect,this will only create a javascript error because b() isn't a function,
You're wrong, it's not an error. b becomes a reference to function a. I actually use this technique often, though in slightly different ways.In the example you provided, b only contains the return value of a. If a happened to change, b wouldn't be updated.
Link to comment
Share on other sites

function a() {	alert("test");}b = a;a = function() {	alert("testing");}b();

All we have demonstrated above is JavaScript's treatment of functions as first-order variables (unlike, say, PHP, which uses function tables instead and requires you to call rename_function().

a = function() {	this.d = "test";	this.b = function() {		alert(this.d);	}}var e = new a();f = e.b;a.d = "testing";e.b();f();

Link to comment
Share on other sites

is new a() the reference?I don't get it
"new" basically creates a copy of an object, as was defined (well, technically it "creates a new instance of an object", but what I'm describing is what "new instance" means), so no. "new" is actually the way it's not by reference.Just keep in mind that
function a()

and

var a = function()

are equivalent, and that objects (functions are objects in JavaScript) are passed by reference, so in

var a = function() {};var b = a;b();

the function in the "a" variable is passed by reference to the "b" variable, and therefore "b()" executes the function in the "b" variable, which is the function in the "a" variable.

Link to comment
Share on other sites

In JavaScript, objects = functions ⊂ variables, which is very useful. In PHP and many other programming languages, objects ≠ functions ≠ variables.

Link to comment
Share on other sites

(function(){	b = a;	a = function() {	    alert("testing");	}	b();	function a() {	    alert("test");	}}())

this should not work if everything were just variables, but it does.this is the same thing as above, b becomes the function known to the environment as a...

Note - it is not possible to actually call by reference in JavaScript.
if that's true, then how can this be explained?
var ray=[1,2,3];function modByRef(x){  x[1]=999;}alert(ray)  // shows 1,2,3modByRef(ray); //(no return, no use of "ray" in function)alert(ray) //  1,999,3

perhaps we are arguing semantics and there is a point you might be getting at, but i don't know what it would be.care to elaborate?

Link to comment
Share on other sites

How do you figure that?it looks to me like b is set to the function named a, which is not the same as a variable named a.
Why not?
if that's true, then how can this be explained?
That's interesting, I didn't think of that behaviour. Gah, what would you call that? It's not technically passing by reference....
var ray={"a" : 1};function modByRef(x){	x.a = 2;}alert(ray.a);modByRef(ray);alert(ray.a);

Link to comment
Share on other sites

there is more than just first-order variables at work here, for example:
This code runs exactly as expected:
b = a;a = function() {	alert("testing");}b();function a() {	alert("test");}

This shows an alert box with "test". Why is that? That function is defined at the end right? So why would that show "test" when you're assigning b to a all the way at the top, and then executing it after you've redefined a? Here's a hint: if you remove the last function definition of a, you get an error.When you define a function like this:function a() {}That function gets defined before the code executes. This style of defining a function:a = function() {}is an inline declaration, that does not get defined before the code executes, it gets defined whenever the execution gets to that part.So, what happens when this code runs is that first the function a gets defined. Then, this gets executed:b = a;So now b points to the same function that a was originally defined as, the function that alerts "test". Then the code redefines a (which does not affect B), and then executes b, which still executes the original a function.So, this is behaving exactly as expected. You're defining a function, then assigning it to another variable, then redefining it, and at the end you have b pointing to the original a function, and a pointing to a new function.Javascript doesn't really distinguish function identifiers from variable identifiers, it just has identifiers. You can use a certain identifier to refer to a function at one point, redefine it to refer to a value, array, object, etc, and redefine it again to refer to another function.The code you showed is the exact same as this:

function a() {	alert("test");}b = a;a = function() {	alert("testing");}b();

It doesn't matter where you have that original definition of a, it's still going to get defined before anything executes.

Link to comment
Share on other sites

EDIT: I started writing this before JSG posted, so I may be duplicating or even saying something stoopid. EDIT 2. I cleaned up some vocabulary.>>>>There is a concept called "copy on write." I believe most modern languages (especially the loosely typed ones) are implemented this way. (PHP certainly is.) As I recall, the JavaScript spec mostly describes the language from a programmers standpoint; it doesn't specify how the interpreter itself should work. So who really knows what goes on under the hood? Anyway, consider:

a = "Hello. I love you. Won't you tell me your name?";b = a;

In this situation, a memory location is allocated for the value assigned to a. When b is assigned the value of a, separate memory is NOT allocated for it. b points to the same memory location that a points to (or it points to a pointer that does) and that will be the situation until the value of a or b changes. At that point, additional memory is allocated, and each identifier points to a unique location.So in this sense, all passing and copying is done by reference. (It always is anyway, but that's a different matter.)Computer science likes to distinguish between primitive datatypes and complex datatypes. I think a primitive type corresponds (I'm not geek enough to be sure) to a first-class object. But in high-level languages, these are concepts, not mechanical realities.I mean this: We think of a as pointing to a string. But in javascript a string is an object. It has methods and properties. Are those copied also, or are they just passed by reference? Even if it's the latter, when you re-prototype a string, say by adding a new method, the new method gets assigned a new chunk of memory, and the string object is somehow associated with it. What we call the "value" of the string is really just one of its properties. It exists somewhere in RAM, and the other properties do also. Best guess says that the original properties (e.g., a.match ) are NOT copied. a.match points to the same thing that every string.match points to. UNLESS a.match is reassigned. And then it points to a new place.Seems to me that what assignment operators do in the case of a string, array, {object}, or function, is really a matter of convenience for the programmer. For one datatype it does one thing; for another datatype it does a different thing. We call a javascript string a primitive or first-class object because of the way it behaves in a script, NOT because of the way memory is or is not allocated. It is convenient to say that passing a string to a function means passing a copy of the string. But what's really happening is that argument.value (let's pretend that's a real thing) suddenly points somewhere different. And I'm not even certain that argument.value even exists as a pointer until something is passed into it. Sure, we declare a function with arguments, but maybe that's a programming convenience also. Like all javascript variables, they aren't typed. And the arguments array of a function is completely dynamic. When you declare an integer in C, a word-length chunk of memory is allocated. When you declare a "string", you specify a number of characters. The allocation is REAL. What happens when you declare a var in JavaScript? An entry in a lookup table is created? And probably the entry doesn't point anywhere yet?As to functions. I knew what rnd me's array experiment would turn up, but I didn't think of it till now. Anyway, I tried something like it that I'd never bothered with before. I was surprised by the result. Consider these:

a = "Hello"; b = a;b==a // returns truea = [1,2,3];b = a;b == a // returns falsefunction a () {	alert ("Hello");}b = a;b == a // returns TRUE

This suggests to me that in our casual way of discussing things, functions really are first-class objects, as Synook said above. So from a programmer's standpoint, passing a function means passing by value. (Not to be confused with a function's return value, which is the distinction we mostly talk about on this board.)I'm sure the "copy-on-write" principle is still in effect, though. And since I'm not aware of any way to modify a javascript function without destroying it (anyone?) I suspect that the interpreter never actually copies a function's "value." (There is only ever one entity in RAM, and different identifiers all point to that entity.) So from the interpreter's standpoint, passing a function (like everything else) really does mean passing by reference, and "copies" of the function always point to the original location/entry.I'm sure I've messed up some vocabulary. If I've messed up a concept, please someone jump in and say so. I'm a hack, not a scientist.

Link to comment
Share on other sites

This code runs exactly as expected:Javascript doesn't really distinguish function identifiers from variable identifiers, it just has identifiers. You can use a certain identifier to refer to a function at one point, redefine it to refer to a value, array, object, etc, and redefine it again to refer to another function.
but what about:
var a = function b(){	alert(;}b=a;b();

that does seem to make a distinction, and it's not closure or first-order vars at work...functions are complicated, there are at least 3 different kinds (with differing properties), and several sub-roles.the overlap of also being an object only adds to the confusion...

Link to comment
Share on other sites

In this case:

var a = function b(){	alert('b');}

This does not create a function called b, this creates a function called a. b is undefined at this point. When a function is on the right-hand side of an assignment operator it does not give the function a name, it just assigns the anonymous function to whatever is on the left-hand side of the assignment. The only reason your code works when you run b() is because you explicitly assign b to a.

functions are complicated, there are at least 3 different kinds (with differing properties), and several sub-roles.
I disagree, functions are pretty straight-forward. What do you mean by three kinds of functions with sub-roles? There are only functions, and all functions are methods on another object. That's about it.
Link to comment
Share on other sites

I suspect rnd me refers to the different syntax for declaring "normal functions" and lambda functions.But yeah, they're all just functions, and as far as I know, the only accessible property they have outside the function value is the prototype property, which I guess they "inherit" from the Object prototype because I don't know what use a function might have for a prototype property. (That was a very long sentence!)And yeah, before b=a, b is undefined. a = function b does nothing to b.Don't you love being able to test #### out in FF's Error Console? I even use it to rough out regexes for PHP. Saves lot's of time. (But Firebug bloops out the console, right? Is there still a way to get instant feedback on a snippet?)

Link to comment
Share on other sites

JavaScript is a class-free language.JavaScript does not have classes, but we can program as though it does.
Correct. JavaScript is a prototyped language. Did you misunderstand my use of the word "class"? A "first-class object" has nothing to do with a "class" in OOP.http://en.wikipedia.org/wiki/First-class_objectMy apologies if I misunderstand you.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...