handler函数的主要作用是将lua对象及方法包装为一个匿名函数,用来做回调函数。
许多功能都需要传入一个 Lua 函数做参数,然后在特定事件发生时就会调用传入的函数。例如触摸事件、帧事件等等。
在解释handler函数的原理之前,首先需要了解lua中 "." 和 ":" 还有 "..."的用法。
handler函数定义的位置 /src/cocos/cocos2d/functions.lua。
函数定义源码:
--[[
@param obj lua对象
@param function method 对象方法
--]]
function handler(obj, method)
return function(...)
return method(obj, ...)
end
end
由此不难发现handler通过接收的两个参数obj, method创建了一个匿名函数并将其返回,并且调用匿名函数时所传入的参数也将传入method方法中,作为obj后面的参数。
以下两段代码的对比显示了handler函数的作用。
local cls = {}
function cls:test()
self._m = "hello world"
end
local clsb = {}
cls.test(clsb)
print(clsb._m)
print(cls._m)
--[[
上述代码输出结果:
hello world
nil
--]]
是的,没有看错,cls中的self变成了clsb。
我们再运行如下代码:
function handler(obj, method)
return function(...)
return method(obj, ...)
end
end
local cls = {}
function cls:test()
self._m = "hello world"
end
local clsb = {}
--cls.test(clsb)
handler(cls, cls.test)() -- 等同于 cls.test(cls)
print(clsb._m)
print(cls._m)
--[[
上述代码输出结果:
nil
hello world
--]]