In JavaScript
, you will often see functions which say document.getElementById("element").someFunction();
or $("element").someFunction();
instead of someFunction($("element"));
. Where someFunction(element)
looks a little like the following code.
someFunction(element) {
//element.doSomething();
}
My question is how do you make a function which manipulates the element it is attached to instead of manipulating an element passed through as an argument?
You can achieve it using prototype
// `getElementById` returns a `Element` object so extend it's prototype
Element.prototype.someFunction = function(){
// this.somethig
}
document.getElementById("element").someFunction();
Element.prototype.someFunction = function() {
console.log(this.value)
}
document.getElementById("element").someFunction();
<input value="abc" id="element" />
Note : It's really bad practice to extend prototype of native object.
You are looking for prototypes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
element.prototype.someFunction = function(){
this.doSomething(); // this refers to element
}
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