谁能告诉我这段代码的含义吗?
var func = tool[ev.type];
if (func) {
func(ev);
}
tool 是在这句话中声明的函数。
最佳答案
它引用函数(对象)“工具”的属性,该属性本身显然包含另一个函数。进行测试以确保该函数存在,然后调用该函数。
tool是一个充满事件处理程序的对象,对象“tool”中的属性名称对应于不同类型的事件。该代码根据事件“类型”引用“工具”对象中的属性。例如:
var tool = {
'click': function(evt) {}, // event handler for click
'mousedown': function(evt) {}, // event handler for mousedown
'mouseup': function(evt) {}, // event handler for mouseup
}
// User presses the mouse button down and doesn't release.
// ev.type == 'mousedown'
//
// Save the property value (which should be an event handler)
// to a variable.
var func = tool[ev.type];
// Make sure func is defined before attempting to invoke it.
if (func) {
// func is defined, invoke it and pass the event object to it
func(ev);
}
希望这有帮助! :)
关于javascript - 对象 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961110/