simple
simple

Reputation: 1091

does var onload mean that it should run when page is loaded

// test.js //

    var testObj = {};
    testObj.init = function(){
        console.log('google');
    }

var onload = testObj.init;

/// what does it mean, does it mean it gets executed when script loaded or what, I just can't understand it as it is not looging into console anything under Google Chrome plugin...

Upvotes: 1

Views: 1518

Answers (6)

pop850
pop850

Reputation: 3157

Nothing is logged because you are simply setting onload to be a pointer to the function testObj.init which only gets the function's code. To actually run it, you must call testObj.init().



More about onload…

onload is a property of an HTML element that can be set to run javascript. For example:

<html>…
… <body onload="testObj.init()"> …
…</html>

This means that when the "body" element is loaded, the function testObj.init() is run.


The "onload" property can also be attatched by javascript, as in:

window.onload=myFunction();

Upvotes: -1

ChaosPandion
ChaosPandion

Reputation: 78282

Think of it like giving your dog 2 names:

var spot = new Dog();
var comeHereSpot = function ()  { return spot; }    
var comeHereBoy = comeHereSpot;

Whether you call comeHereSpot or comeHereBoy the same dog will come running.

Upvotes: 2

Sasha Chedygov
Sasha Chedygov

Reputation: 130877

In your code, onload is simply the name of a local variable. The var keyword declares local variables. You're setting the value of onload to testObj.init, which is a function that prints 'google' to the console.

To make it run the function on page load, set window.onload to the value of the function.

window.onload = testObj.init;

Or, better yet, use event handlers to attach an "onload" event to the window object. (To make this easier, use a JavaScript library such as jQuery, but I recommend you first learn how it all works.)

Upvotes: 0

Guffa
Guffa

Reputation: 700592

No, it only means that you assign it to a variable named onload.

Depending on the scope of the code it might actually work, if the variable name collides with the onload property of the window object. In that case a variable would not be created, but it would use the existing property instead. You should not rely on this behaviour though, you should always specify it as a property of the object:

window.onload = testObj.init;

Upvotes: 0

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110982

It means that variable onload is a reference to the function testObj.init. onload() will execute the function and output 'google' to the console.

Upvotes: 0

Hugo Migneron
Hugo Migneron

Reputation: 4907

It just means that your variable onload now points to

function(){
    console.log('google');
}

onload is just the name of a local variable here.

Upvotes: 0

Related Questions