views:

1245

answers:

3

Hi,

if I have:

function init(t,y,u) 
{
   alert(t + " " + y + " " + u);
}

// String.prototype.add = init(5, 6, 7);  // 1)   
// window.onload = init(5,6,7); // 2)

in the 1) init will be executed and then it pointer assegned to String.prototype.add but in the 2) the function is only executed one time... but why not two times also when the onload event is raised?

Thanks

+8  A: 

in the 1) init will be executed and then it pointer assegned to String.prototype.add

No it won't. The function will simply be executed and its return value (undefined) will be assigned to String.prototype.add. No function pointer will be assigned. To do this, you need to return a function!

function init(t,y,u) {
    alert(t + " " + y + " " + u);
    return function () { alert('function call!'); };
}
Konrad Rudolph
To return itself: return arguments.callee;
some
+4  A: 

You may want something like:

String.prototype.add = function () { init(5, 6, 7); };
abababa22
Did he ask for code?
Georg
Do you need help reading his question?
abababa22
+3  A: 

This is what happens with your code:

  • Defining a function called init with three parameters that will be alerted when the function is called.
  • Calling the function init with parameters 5,6,7 (an alert will popup) and assign the result (undefined) to String.prototype.add
  • Calling the function init with parameters 5,6,7 (an alert will popup) and assign the result (undefined) to window.onload

If the code above was executed before the window.onload event was fired, nothing will happen when it is fired, because it is set to undefined.

some