⬆️ ⬇️

Calling the Javascript method without actually calling it

image Sometimes we are just lazy. Especially when it comes to writing code. And although the parentheses in the function call do not lead to redundancy, sometimes they can still bore, especially when the javascript method does not need arguments passed to it. Sometimes it just bothers you.



Oddly enough, all this is not hard to do in Javascript, like most other methods that are called ... toString is probably one of many well-known, but also, like valueOf, which does more or less the same thing, but numerical (and some other types in JavaScript.



The easiest way to call it, including the plus sign:



+myFunction;


')

what actually means:



window.parseFloat(myFunction.valueOf());




So, all we need to do is to force the valueOf method to execute the function passed to it for execution:



Function.prototype.valueOf=function(){this.call(this); return 0;};




... and suddenly the plus sign becomes everything we need for this call.



Especially in OOP, you can have a lot of similar calls, but you can fix these methods so that they are called within the method itself:



Function.prototype.fix=function(s){var t=this; return function(){ return t.apply(s,arguments); }; };




Using this method in the constructor, you can make a wrapper:



var Foo= function (){

this .myMethod= this .myMethod.fix( this );

};






or automating a little:

var Foo= function (){

for ( var i in this )

if ( typeof ( this [i])== "function" )

this [i]= this [i].fix( this );

};




and finally, finish with a complete example (after a small OOP refactoring):



  1. var StandardClass = function () {};
  2. StandardClass.prototype.initMethods = function () {
  3. for ( var i in this )
  4. if ( typeof ( this [i]) == ” function ” && this [i] .dontWrap! == true )
  5. this [i] = this [i] .fix ( this );
  6. };
  7. StandardClass.prototype.initMethods.dontWrap = true ;
  8. Function.prototype.fix = function (s) {
  9. var t = this ;
  10. return function () {
  11. return t.apply (s, arguments);
  12. };
  13. };
  14. Function.prototype.valueOf = function () {
  15. this .call ( this );
  16. return 0;
  17. };
  18. var Foo = function (name) {
  19. this .initMethods ();
  20. this .name = name;
  21. };
  22. Foo.prototype = new StandardClass;
  23. Foo.prototype.showName = function () {
  24. alert ( this .name);
  25. };
  26. Foo.prototype.showNameUpperCase = function () {
  27. alert ( this .name.toUpperCase ());
  28. };
  29. var myFoo = new Foo (“Hello World”);
  30. + myFoo.showName;
  31. + myFoo.showNameUpperCase;
* This source code was highlighted with Source Code Highlighter .

Source: https://habr.com/ru/post/90432/



All Articles