1

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())
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121
  • check this one [link](http://stackoverflow.com/questions/9354298/how-do-i-write-an-extension-method-in-javascript) – vikscool Oct 12 '16 at 10:15
  • Have a look in to [Javascript Prototype](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) and this [MDN article](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype) might help too. – Tigger Oct 12 '16 at 10:15
  • you should try to read about jquery plugins, Here there is a sample: https://learn.jquery.com/plugins/basic-plugin-creation/ – Mayday Oct 12 '16 at 10:18

2 Answers2

3

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/

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

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">
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109