For example I want a function that is used by many elements to get the attributes of the calling element.
function example(){
var name = //name of the calling element "$(this).attr('name')"
}
<button name="somename1" onclick="example()">Button1</button>
<button name="somename2" onclick="example()">Button2</button>
so if the button named 'somename1' calls the function, the variable 'name' will be assigned to 'somename1' and so if 'somename2' called it, it will be assigned to 'somename2'
To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.
In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
Use This:
function exampleFunction(exampleElement) {
var name = exampleElement.name;
}
<button name="somename1" onclick="exampleFunction(this)">Button1</button>
<button name="somename2" onclick="exampleFunction(this)">Button2</button>
But if you use jquery, you could do
$('button').click(function() {
var name = $(this).attr('name');
});
Without the onclick
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With