JavaScript Event listener defined inside object

I recently saw a listener defined inside method of object bound to nothing. Nice example is this

var obj={
    shout:function(){
        onclick = function(){
            alert("hi");
        }
    }
}
obj.shout()

This works like window.onclick=shout;

also when we redefine function like this

var obj={
    shout:function(s){
        onclick = function(s){
            alert(s);
        }
    }
}
obj.shout('hi')

It outputs [Object mouse event]

How does it get automaticly binded to window object? This should point to obj object and if onclick gets binded to this of shout which refers to obj (my suspicion ) how come it works with window object??

Answer:1

How does it get automaticly binded to window object?

Because onclick is a property of window, and all properties of window are global variables. Since you haven't declared an onclick variable anywhere, the onclick = function... line is assigning to the global.

Answer:2

please help me to build following logic, here is code: <button onclick="zoomin()">Zoom In</button> function zoomin(){ var myImg = document.getElementById("img"); var i = 0; i++; ...

please help me to build following logic, here is code: <button onclick="zoomin()">Zoom In</button> function zoomin(){ var myImg = document.getElementById("img"); var i = 0; i++; ...

I've created some sample code below. You can delete items simply by clicking the text you want to delete (or the li element). When you look at the network tab when you delete, you get back both a ...

I've created some sample code below. You can delete items simply by clicking the text you want to delete (or the li element). When you look at the network tab when you delete, you get back both a ...

My authenticate.php file is returning an object Json: [{"u_id":"1","u_name":"Nabeel" }] Here is my js: success: function(result) { var obj=$.parseJSON(result); alert(result); //[{"u_id":"1"...

My authenticate.php file is returning an object Json: [{"u_id":"1","u_name":"Nabeel" }] Here is my js: success: function(result) { var obj=$.parseJSON(result); alert(result); //[{"u_id":"1"...

I'm writing a program that calculates the price of painting rooms in a house. The program asks the user a couple of questions and the user must input certain answers regarding the topic. The program ...

I'm writing a program that calculates the price of painting rooms in a house. The program asks the user a couple of questions and the user must input certain answers regarding the topic. The program ...

  1. javascript repeat validation