jsÖÐthis¼´ÊÇʲô
ÔÚ javascript ÖУ¬this Ö¸ÏòÄ¿½ñÖ´Ðк¯ÊýµÄ¹¤¾ß¡£this µÄֵȡ¾öÓÚº¯ÊýµÄŲÓ÷½·¨ºÍÉÏÏÂÎÄ¡£³£¼ûÇéÐÎÏ£º×÷ΪҪÁìŲÓãºÖ¸Ïò°üÀ¨¸ÃÒªÁìµÄ¹¤¾ß¡£×÷Ϊº¯ÊýŲÓãºÖ¸ÏòÈ«¾Ö¹¤¾ß£¨ä¯ÀÀÆ÷Ϊ window£¬node.js Ϊ global£©¡£×÷Ϊ½á¹¹º¯ÊýŲÓãºÖ¸Ïòн¨ÉèµÄ¹¤¾ß¡£Í¨¹ý call() »ò apply() ŲÓãºÖ¸ÏòÖ¸¶¨µÄ¹¤¾ß¡£
JavaScript ÖÐµÄ this
JavaScript ÖÐµÄ this Òªº¦×ÖÖ¸ÏòÄ¿½ñÕýÔÚÖ´Ðк¯ÊýµÄ¹¤¾ß¡£ËüÊÇ JavaScript ×îÇ¿Ê¢µÄÌØÕ÷Ö®Ò»£¬µ«Ò²ÊÇ×îÁîÈËÒÉÐĵÄÌØÕ÷Ö®Ò»¡£
this µÄÖµ
this µÄֵȡ¾öÓÚÒÔÏÂÒòËØ£º
ŲÓú¯ÊýµÄ·½·¨£º¿ÉÒÔͨ¹ýËÄÖÖ·½·¨Å²Óú¯Êý£º×÷ΪҪÁì¡¢×÷Ϊº¯Êý¡¢×÷Ϊ½á¹¹º¯Êý»òͨ¹ý call() »ò apply() ÒªÁì¡£
ÉÏÏÂÎÄ£ºÔÚ²î±ðµÄŲÓÃÉÏÏÂÎÄÖУ¬this ¿ÉÄÜÖ¸Ïò²î±ðµÄ¹¤¾ß¡£
³£¼ûÇéÐÎÏ嵀 this
ÒÔÏÂÊÇ this ÔÚ³£¼ûÇéÐÎϵÄÖµ£º
×÷ΪҪÁìŲÓãºÖ¸Ïò°üÀ¨¸ÃÒªÁìµÄ¹¤¾ß¡£ÀýÈ磬this.name ÌåÏÖŲÓøÃÒªÁìµÄ¹¤¾ßµÄ name ÊôÐÔ¡£
×÷Ϊº¯ÊýŲÓãºÖ¸ÏòÈ«¾Ö¹¤¾ß£¨ÔÚä¯ÀÀÆ÷ÖÐΪ window ¹¤¾ß£¬ÔÚ Node.js ÖÐΪ global ¹¤¾ß£©¡£
×÷Ϊ½á¹¹º¯ÊýŲÓãºÖ¸Ïòн¨ÉèµÄ¹¤¾ß¡£
ͨ¹ý call() »ò apply() ŲÓãºÖ¸ÏòÖ¸¶¨µÄ¹¤¾ß¡£
ʾÀý£º
ÏÂÃæµÄʾÀý˵Ã÷Îú this µÄÖµÔÚ²î±ðÇéÐÎÏ£º
// ×÷ΪҪÁìŲÓà const person = { name: "John", getName: function() { console.log(this.name); } }; person.getName(); // Êä³ö: John // ×÷Ϊº¯ÊýŲÓà function getName() { console.log(this.name); } getName(); // Êä³ö: undefined (Ö¸ÏòÈ«¾Ö¹¤¾ß) // ×÷Ϊ½á¹¹º¯ÊýŲÓà function Person(name) { this.name = name; } const person1 = new Person("John"); console.log(person1.name); // Êä³ö: John // ͨ¹ý call() ŲÓà const obj = { name: "Jane" }; getName.call(obj); // Êä³ö: Jane
µÇ¼ºó¸´ÖÆ
Ã÷È· this µÄÖµ¹ØÓÚ JavaScript ¿ª·¢ÖÁ¹ØÖ÷Òª¡£ËüÔÊÐíÄãÇáËɵػá¼ûÄ¿½ñ¹¤¾ßµÄÊý¾ÝºÍÒªÁì¡£
ÒÔÉϾÍÊÇjsÖÐthis¼´ÊÇʲôµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡