Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function close() {} [duplicate]

Tags:

javascript

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() ?

like image 340
mannaris Avatar asked Dec 15 '22 02:12

mannaris


1 Answers

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.

like image 92
2 revs Avatar answered Dec 17 '22 01:12

2 revs