之前写CocosLua和CocosJS时经常会遇到类成员函数中调用内嵌函数时的this传递问题,最近发现Javascript中可以通过使用箭头函数简化这个this的闭包问题,先给出测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class clsTest { constructor(var1) { this ._var1 = var1; } foo() { console.log( "1111" , this ._var1); (() => { console.log( "2222" , this ._var1); })(); ( function () { console.log( "3333" , this ); })(); let self = this ; ( function () { console.log( "4444" , self._var1); })(); } } let objTest = new clsTest(10); objTest.foo(); |
JSFiddle:https://jsfiddle.net/u0yconbg/2/
为了简化示例代码,内嵌函数都写成了自调用的形式,可见333时的内嵌函数调用this是undefined,所以4444时在调用函数前声明了self用于闭包进内嵌函数访问this,(Lua中一般是local this = self),而2222的内嵌函数是通过箭头方式声明的,可见log中成功输出了clsTest类对象的_var1成员变量值,也就是说this被自动传递了,为此特意查了下文档:
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
来自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
博主友情提示:
如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。
加载更多