Skip to content

Instantly share code, notes, and snippets.

@miere
Created October 20, 2014 19:53
Show Gist options
  • Select an option

  • Save miere/1b13cf6bb234163f6ebd to your computer and use it in GitHub Desktop.

Select an option

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
/**
* 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 )
}
}
}
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