3

reading the code I found out code like this

window["foo"]=
   function() {
      alert("foo");
   }

And if I call the function for example on onclick("foo()") I will get "foo" So what is window["foo"] ?

Serio
  • 383
  • 2
  • 9

2 Answers2

4

foo is function declared as a prop in the window object which is the top level scope . which means your variable is accessed globaly from any place in you code , and its accessible like this :

window["foo"]=
   function() {
      alert("foo");
   }


window["foo"]();
window.foo();
foo(); // this is your attempt on onclick
HijenHEK
  • 1,043
  • 1
  • 3
  • 11
3

Foo Word :

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. From Here

So, "Foo" is just popular word between programmers like Hello World for the first program to learn code.

Explanation for Code :

Your code create a string property under window object called "Foo" and assign function to this property which is the alert function So when Javascript listen to a property called Foo (e.g the onclick function) it will call the alert function which you will see alert called "Foo".

Examples :

Example for Javascript Objects & Properties :

// JavaScript Object Properties
// There are two different ways to access an object property.
// You can use .property or ["property"].


var person = {
  firstname:"John",
  lastname:"Doe",
  age:50,
  eyecolor:"blue"
};

console.log(person["firstname"] + " is " + person["age"] + " years old.");

Documentation Links :

Documentation for Javascript Objects & Properties.

Kevin M. Mansour
  • 1,932
  • 5
  • 14
  • 28