Javascript inline function call
I have a question about calling a built-in function in javascript.
This example works:
<button onclick="{alert($(this).text());}">Testing</button>
While this doesn't work:
<button onclick="function(){alert($(this).text());}">Testing</button>
My question is, why does the second case not work while the first does?
I ran into this problem using jQuery-UI droppable:
$( ".selector" ).droppable({
drop: function( event, ui ) {}
});
Droppable uses this syntax as well (without function()
). Why is this?
source to share
Lets break this sample into sample
<button onclick="{alert($(this).text());}">Testing</button>
It will be the same as in pure javascript.
document.querySelector('button').addEventListener('click', function() {
{
alert($(this).text());
}
});
It is a little weird to add extra curly braces, but this is completely allowed and the code inside will be executed. For your second sample, it gets really weird though.
<button onclick="function(){alert($(this).text());}">Testing</button>
It will be the same as here.
document.querySelector('button').addEventListener('click', function() {
function() {
alert($(this).text());
}
});
In other words, when you click on a button, you are declaring a new function, but you will never call it. To get around this, you would need to wrap it in paranthesis and then call .call(this)
on a function that is executing with the same this
as the caller.
document.querySelector('button').addEventListener('click', function() {
(function() {
alert($(this).text());
}).call(this);
});
Or in your style.
<button onclick="(function(){alert($(this).text());}).call(this)">Testing</button>
source to share
Since the brackets are overkill and probably ignored:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="alert($(this).text());">Testing</button>
If you wanted to encapsulate it in a function and run it as such, I suppose you would have to call it yourself:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="(function(){alert($(this).text());})();">Testing</button>
But then the meaning this
becomes unrelated.
Syntax droppable
is something completely different - you can think of it like this:
var configObj = { // this isn't a function, it a config object
drop: function( event, ui ) {} // this is a function value of the property drop
}
$( ".selector" ).droppable(configObj);
source to share