Created
October 20, 2014 19:53
-
-
Save miere/1b13cf6bb234163f6ebd to your computer and use it in GitHub Desktop.
fake polymorphic method. It will switch between number of arguments but will make no distinction between types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * fake polymorphic method. It will switch between number of arguments but will | |
| * make no distinction between types. | |
| */ | |
| function Method( args ){ | |
| if ( this instanceof Method ) { | |
| this.expectations = {} | |
| this.target = args || window | |
| } else | |
| return new Method() | |
| } | |
| Method.prototype = { | |
| parameters: function( numberOfParameters, callback ){ | |
| this.expectations[ numberOfParameters ] = callback | |
| return this | |
| }, | |
| invoke: function(){ | |
| var method = this.expectations[ arguments.length ] | |
| if ( !method ) | |
| throw "Invalid number of arguments" | |
| return method.apply( this.target, arguments ) | |
| }, | |
| callable: function(){ | |
| var self = this | |
| return function(){ | |
| return self.invoke.apply( self, arguments ) | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var myObject = { | |
| __name: null, | |
| name: Method() | |
| .parameters( 0, function(){ return myObject.__name } ) | |
| .parameters( 1, function( v ){ this.__name = v } ) | |
| } | |
| console.log( myObject.name() ) // will print null | |
| myObject.name( "Joseph Climber" ) | |
| console.log( myObject.name() ) // will print "Joseph Climber" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment