ÎÊÌâÃèÊö
µ±ÎÒʹÓÃ×îР(1.0) °æ±¾µÄ¿§·È½Å±¾Ê±£¬Ò»¸ö¼òµ¥µÄ javascript Êä³ö¿´ÆðÀ´ÏñÕâÑù(ĬÈÏÇé¿öÏÂ):
When I use the latest (1.0) release of coffee-script, a simple javascript output looks like this (by default):
(function() {
var a;
a = 1;
}).call(this);
.call(this) ÓÐʲô×÷ÓÃÒÔ¼°Ìí¼ÓËüµÄÔÒòÊÇʲô?
What does .call(this) do and what would be the reason to add it?
ÍƼö´ð°¸
ËüÕýÔÚ´´½¨Ò»¸öº¯Êý£¬È»ºóʹÓø¸º¯Êý/¶ÔÏó·¶Î§µ÷ÓÃ×ÔÉí.
It's creating a function and then calling itself with the parent function/objects scope.
.call ºÍ .apply Êǵ÷Óú¯ÊýµÄ²»Í¬·½·¨.Äú»ù±¾ÉÏ´´½¨ÁËÒ»¸öº¯Êý£¬³ýÁËÔÚ×Ô¼ºµÄ·¶Î§ÄÚÉèÖà a=1 Ö®Íâʲô¶¼²»×ö.
.call and .apply are different methods of invoking a function. You basically created a function that does nothing except set a=1 within its own scope.
ÔÚ javascript ÖÐÄãÐèÒªÒâʶµ½Ã¿¸öº¯Êý¶¼ÊÇÒ»¸ö¶ÔÏ󣬶ø this
ÊÇÖ¸µ±Ç°µÄ¶ÔÏó/º¯Êý.ʹÓà .call(this)
¸²¸Çº¯ÊýÄÚµÄ this
²¢½«ÆäÌ滻Ϊµ÷ÓÃÉÏÏÂÎÄÖеÄÄǸö.
In javascript you need to realize that every function is a object, and this
is what refers to the current object/function. Using .call(this)
overrides this
from within the function and replaces it with the one from the calling context.
Õâƪ¹ØÓÚΪʲôҪʹÓÃjavascriptº¯Êý°ü×°Æ÷(ÔÚcoffeescriptÖÐÌí¼Ó)¡°.call(this)"?µÄÎÄÕ¾ͽéÉܵ½ÕâÁË£¬Ï£ÍûÎÒÃÇÍƼöµÄ´ð°¸¶Ô´ó¼ÒÓÐËù°ïÖú£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö¸ú°æÍø£¡