5

I've created a function in JS named close

function close() {...}

and have an onclick call

onclick="close()"

but it won't work. If I rename the function to whatever, it works. Could it be that it is forbidden to use a function in JS named close() ?

adeneo
  • 312,895
  • 29
  • 395
  • 388
mannaris
  • 63
  • 8
  • you have made it as ( function close() {} ) ,it is supposed to be an IIFE which has to be called right away,like ( function close() {} ) (),this if you are using it for click functionality i suggest make it function close(){} – Geeky Nov 06 '16 at 15:03
  • 1
    @T.J.Crowder - > http://stackoverflow.com/questions/8550828/onclick-calling-hide-div-function-not-working – adeneo Nov 06 '16 at 15:22
  • @adeneo: Nice one! – T.J. Crowder Nov 06 '16 at 15:29

3 Answers3

6

In order to be used in an onxyz-attribute-style event handler, your function has to be a global. Don't call a global function close, because globals become properties of the window object,1 and it has a property called close (referring to a host function that closes the window). You aren't allowed to overwrite that property, and so it's the built-in one that ends up getting used. (And then the close request is ignored, there are various reasons windows may not allow you to close them via code.) Use another name (or better yet: make it not a global and hook it up with modern event handling).


1 Except in ES2015 and later if you use let or const or class to create the global.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

close is a method of window. Like all objects from window, you can call it without window prefix.

console.log(typeof close);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

It's because in the global scope, where inline event handlers live, there already is a window.close function that can't be overwritten, and you're calling that function, not your own function named close()

adeneo
  • 312,895
  • 29
  • 395
  • 388