×ðÁú¿­Ê±¹ÙÍøµÇ¼

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¼´ÊÇʲôµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
ÍøÕ¾µØͼ