Babelã使ãã¨ã¢ãã¼é¢æ°å ã®thisãundefinedã«ãªã
ãããããåé¡ã«ç´é¢ããã®ã§ãã¡ã¢ãã¦ããã
åé¡
次ã®ããã«ãjQueryã§ã³ã¼ã«ããã¯é¢æ°ã«ã¢ãã¼é¢æ°ãç¨ããã¹ã¯ãªãããè¨è¿°ããã
$("item > title").each(() => { let title = $(this).text(); console.log(title); });
ãã®ES6ã®æ§æããBabelã§ES5ã¸ãã©ã³ã¹ãã¤ã«ããã¨...
$("item > title").each(function(idx) { var title = $(undefined).text(); console.log(title); });
ã¢ãã¼é¢æ°ã®å
ã®this
ãundefined
ã«ãªã£ã¦ãã¾ãã
åé¡ã¯ãã©ããããã©ã³ã¹ãã¤ã«åå¾ã®ãeach
é¢æ°ã§ã®this
ã®æ±ãã®éãã«ãããã®ã®ããã ã
以ä¸ãã·ã³ãã«ãªä¾ãèãã¦ã¿ãã
var arr = [1]; $(arr).each(() => { console.log(this); /* Window {} */ }); $(arr).each(function() { console.log(this); /* Number {} */ }); $(arr).each((idx, value) => { console.log(value); /* 1 */ });
ã¢ãã¼é¢æ°ã®this
ã¯windowãªãã¸ã§ã¯ããæããç¡åé¢æ°ã§ã¯è¦ç´ ãæãã
ãããBabelã«éãã¨ãèªåçã«"use strict"
ã¢ã¼ãã«ãªããã¹ã¯ãªãããå®è¡ããçµæã¯æ¬¡ã®ããã«å¤ããã
/* "use strict" */ var arr = [1]; $(arr).each(() => { console.log(this); /* undefined */ }) $(arr).each(function() { console.log(this); /* 1 */ }) $(arr).each((idx, value) => { console.log(value); /* 1 */ });
"use strict"
ã¢ã¼ããé©ç¨ãããé"use strict"
ã¢ã¼ãã®ã¢ãã¼é¢æ°ã§ã¯windowãªãã¸ã§ã¯ãã«bindããã¦ããthis
ããundefined
ã«ãªã£ã¦ããã
each
é¢æ°å
ã§ã®this
ã¯è¦ç´ ãæãããã¢ãã¼é¢æ°å
ã®this
ã¯ãã®ã³ã³ããã¹ãã®this
ã«çãããã¤ã¾ããthis === windowãªãã¸ã§ã¯ããæãç«ã¤ãå ãã¦ã"use strict"
ã¢ã¼ãã«ããã¦ã¯ããã®ãããªthis
ã¯undefined
ã«ãªããããä»åã®ãããªåé¡ãçºçããã
ã¾ã¨ã
ã¾ã¨ããã¨ãjQueryã®ã³ã¼ã«ããã¯é¢æ°ã§æ³¨æãã¹ãç¹ã¨ãã¦ã¯:
- ç¡åé¢æ°å
ã§ã¯ã
this
ã¯è¦ç´ ãæãã - ã¢ãã¼é¢æ°ã§ã¯ã
this
ã¯ãã®ã³ã³ããã¹ãã®this
ã«çããã
ããã«å ãã¦ãBabelãç¨ããã¨ã"use strict"
ã¢ã¼ããé©ç¨ãããä»åã®ããã«ãwindowãªãã¸ã§ã¯ããæãã¦ããã¢ãã¼é¢æ°å
ã®this
ã¯undefined
ã«ãªãã
解決ç
ãã®çµæãè¸ã¾ããã¨ãä»åã®è§£æ±ºçã¨ãã¦ã¯ã
- ããããã¢ãã¼é¢æ°ãããã
- è¦ç´ ã®å¤ã§ããå¼æ°ã使ã
/* ã¢ãã¼é¢æ°ãããã */ $("item > title").each(function() { let title = $(this).text(); console.log(title); }); /* è¦ç´ ã®å¤ã§ããå¼æ°ã使ã */ /* 第ä¸å¼æ°ãã¤ã³ããã¯ã¹ã第äºå¼æ°ãè¦ç´ ã®å¤ */ $("item > title").each((idx, value) => { let title = $(value).text(); console.log(title); });
å¤åãã£ã¦ããã¨ã¯æãããç解ããµããµããã¦ããã