0

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

3 Answers 3

8

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!'); };
}
Sign up to request clarification or add additional context in comments.

1 Comment

To return itself: return arguments.callee;
5

You may want something like:

String.prototype.add = function () { init(5, 6, 7); };

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.