[英]JS - creating user-defined function for custom js objects
The question is as simple as - is it possible to create a user-defined method for standard js objects like the val
method for input
?问题很简单 - 是否可以为标准 js 对象创建用户定义的方法,例如
input
的val
方法? That is, to do smth like:也就是说,做 smth 像:
function my_new_method()
{
...
}
...
alert($('td input').my_new_method())
Since that is looks like jQuery (not vanilla/standard JavaScript), you can simply use $.fn.my_new_method = // your function
因为它看起来像 jQuery(不是 vanilla/标准 JavaScript),你可以简单地使用
$.fn.my_new_method = // your function
You can read up on how to create a jQuery plugin here: https://learn.jquery.com/plugins/basic-plugin-creation/您可以在此处阅读有关如何创建 jQuery 插件的信息: https : //learn.jquery.com/plugins/basic-plugin-creation/
You can use Object prototype.您可以使用对象原型。
Object.prototype.my_new_method = function() { console.log(this.val()); } $("#test").my_new_method();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' value='abc' id="test">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.