Search code examples
javascriptpropertiesthiselement

Javascript How pass this Keyword to a Function?


Hi every one I would like to modify an a Property from a button ease right jajaja

document.getElementById("button_1").style.visibility = "collapse";

But here I have the id from the object I would like to alter but if i don't know specifically the id because the object's come from a loop I should use "this" the JavaScript Keyword right? like "this.id" to get in to the id of the object it call's example

<input type='button' id='button_1' onclick='alert(this.id)' >Click Me!</button>

That will show the id from that element

When I call a Function

<script>
function Funtion_Alert() {

    alert (this.id);

}
</script>

<input type='button' id='button_1' onclick='Funtion_Alert(this)' >Click Me!</button>

I get in y the alert undefined I need get the id from the element which is being calling the function


Solution

  • This is not how you pass this. this is special, it's a context of your current function invocation.

    Either pass it as an argument, but then you have to call it something else inside the function, like here:

    <script>
    function Funtion_Alert(element) { // <<< note the argument!
    
        alert(element.id); // <<< note the different name!
    
    }
    </script>
    
    <input type='button' id='button_1' onclick='Funtion_Alert(this)' >Click Me!</button>
    

    ...or pass it as actual this, by using Function.prototype.call:

    <script>
    function Funtion_Alert() {
    
        alert(this.id);
    
    }
    </script>
    
    <input type='button' id='button_1' onclick='Funtion_Alert.call(this)' >Click Me!</button>
    <!-- note the .call -->
    

    Otherwise, the this inside the function will be window as explained here, so this.id will essentially be window.id which is not what you want.