简体   繁体   中英

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 ? That is, to do smth like:

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

You can read up on how to create a jQuery plugin here: 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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM