在这里面按钮上的变量名没有了,好看了些,不过如果要是多写几次的话就会觉得,每次都function(){return function(){}},这样好像很麻烦,提出来一个方法不是更好么?
Version 3:
| <script language="javascript" type="text/javascript"> function SomeClass(el) { if(typeof(el) == "string") { el = document.getElementById(el); } el.onclick = this.GetFunction(this, "Show"); } SomeClass.prototype = { Show : function() { alert("Say Hello!"); }, GetFunction : function(Variable, Method) { return function() { Variable[Method](); } } } window.onload = function() { new SomeClass("btnDemo"); } </script> <input type="button" value="Hello" id="btnDemo" /> |
这样每次要绑定方法的时候只要调用GetFunction方法就可以了,重用嘛.但是问题又来了,我要是要传参数怎么办呢?
Version 4:
| <script language="javascript" type="text/javascript"> function SomeClass(el) { if(typeof(el) == "string") { el = document.getElementById(el); } el.onclick = this.GetFunction(this, "ShowAny", "Hello, Robot!"); } SomeClass.prototype = { Show : function() { alert("Say Hello!"); }, ShowAny : function(any) { alert(any); }, GetFunction : function(Variable, Method, Parameter) { return function() { Variable[Method](Parameter); } } } window.onload = function() { new SomeClass("btnDemo"); } </script> <input type="button" value="Hello" id="btnDemo" /> |

