如何使函数在元素后面

How to make a function to go after an element

本文关键字:元素 何使 函数      更新时间:2023-09-26

JavaScript中,您经常会看到函数是document.getElementById("element").someFunction();$("element").someFunction();而不是someFunction($("element"));。其中someFunction(element)看起来有点像下面的代码。

someFunction(element) {
    //element.doSomething();
}

我的问题是,如何创建一个函数来操纵它所附加的元素,而不是操纵作为参数传递的元素?

您可以使用原型来实现它

// `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" />


注意:扩展本机对象的原型是非常糟糕的做法。

您正在寻找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
}