这些代码运作良好.
<input id="mainCheckbox" type="checkbox"/>
...
var controlCheckbox = document.getElementById( "mainCheckbox" ),
...
controlCheckbox["onclick"] = new Function( "controlCheckbox.Notify(controlCheckbox.checked)" );
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
controlCheckbox["onclick"] = controlCheckbox.Notify(controlCheckbox.checked);
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为它不分配函数,而是.Notify立即调用.
但是,您可以使用匿名函数语法来创建函数.
controlCheckbox["onclick"] = function() {
controlCheckbox.Notify(controlCheckbox.checked);
};
Run Code Online (Sandbox Code Playgroud)
这比使用Function构造函数更常见.
这两种方法之间的一个区别是,创建的函数new Function将无法使用封闭的局部变量范围.它就好像是直接在global范围内创建的.
;(function() {
var foo = "bar"; // local variable
var x = new Function("console.log(foo);");
x(); // ReferenceError: foo is not defined
})();
Run Code Online (Sandbox Code Playgroud)
因此,除非您的第一个代码示例中的变量在global范围内,否则它将无法工作,因为该controlCheckbox变量将无法访问.
虽然,因为变量只是对被绑定元素的引用,所以您并不真正需要它,因为您可以this在处理程序中使用它.
controlCheckbox["onclick"] = new Function("this.Notify(this.checked)" );
Run Code Online (Sandbox Code Playgroud)