Created
October 19, 2013 06:58
-
-
Save danimal141/7052465 to your computer and use it in GitHub Desktop.
function overloading sample
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>function overloading</title> | |
</head> | |
<body> | |
<div id="target1" style="width:100px; height:100px;"></div> | |
<div id="target2" style="width:100px; height:100px;"></div> | |
<div id="target3" style="width:100px; height:100px;"></div> | |
<script> | |
function addMethod(object, name, fn) { | |
var old = object[name]; //#1 | |
object[name] = function(){ | |
console.log(arguments); | |
console.log(fn.length); | |
if (fn.length == arguments.length) //#2 | |
return fn.apply(this, arguments) //#2 | |
else if (typeof old == 'function') //#3 | |
return old.apply(this, arguments); //#3 | |
}; | |
} | |
var Target = function(id){ | |
this.target = document.getElementById(id); | |
}; | |
var p = Target.prototype; | |
addMethod(p, "changeColor", function(color_name){ | |
this.target.style.backgroundColor = color_name; | |
}); | |
addMethod(p, "changeColor", function(r, g, b){ | |
this.target.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")"; | |
}); | |
addMethod(p, "changeColor", function(r, g, b, a){ | |
this.target.style.backgroundColor = "rgba(" + r + "," + g + "," + b + "," + a + ")"; | |
}); | |
var target1 = new Target("target1"); | |
target1.changeColor("red"); | |
var target2 = new Target("target2"); | |
target2.changeColor(255, 200, 100); | |
var target3 = new Target("target3"); | |
target3.changeColor(155, 140, 100, 0.3); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment