Calling a Javascript method without actually calling it

Original author: Admin
  • Transfer
imageSometimes we are just lazy. Especially when it comes to writing code. And although parentheses in a 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.

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

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

+myFunction;


which actually means:

window.parseFloat(myFunction.valueOf());


So, all we have to do is get the valueOf method to run the function passed to it:

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


... and suddenly the plus sign becomes all that we need for this challenge.

Especially in OOP, you can have a lot of such 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 by 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 little OOP refactoring):

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

Also popular now: