JavaScript this ¹Ø¼ü´Ê
ʵÀý
var person = { firstName: "Bill", lastName : "Gates", id : 678, fullName : function() { return this.firstName + " " + this.lastName; } };
this ÊÇʲô£¿
JavaScript this ¹Ø¼ü´ÊÖ¸µÄÊÇËüËùÊôµÄ¶ÔÏó¡£
ËüÓµÓв»Í¬µÄÖµ£¬¾ßÌåÈ¡¾öÓÚËüµÄʹÓÃλÖãº
- ÔÚ·½·¨ÖУ¬this Ö¸µÄÊÇËùÓÐÕß¶ÔÏó¡£
- µ¥¶ÀµÄÇé¿öÏ£¬this Ö¸µÄÊÇÈ«¾Ö¶ÔÏó¡£
- ÔÚº¯ÊýÖУ¬this Ö¸µÄÊÇÈ«¾Ö¶ÔÏó¡£
- ÔÚº¯ÊýÖУ¬ÑϸñģʽÏ£¬this ÊÇ undefined¡£
- ÔÚʼþÖУ¬this Ö¸µÄÊǽÓÊÕʼþµÄÔªËØ¡£
Ïñ call() ºÍ apply() ÕâÑùµÄ·½·¨¿ÉÒÔ½« this ÒýÓõ½ÈκζÔÏó¡£
·½·¨ÖÐµÄ this
ÔÚ¶ÔÏó·½·¨ÖУ¬this Ö¸µÄÊÇ´Ë·½·¨µÄ¡°ÓµÓÐÕß¡±¡£
ÔÚ±¾Ò³×îÉÏÃæµÄÀý×ÓÖУ¬this Ö¸µÄÊÇ person ¶ÔÏó¡£
person ¶ÔÏóÊÇ fullName ·½·¨µÄÓµÓÐÕß¡£
fullName : function() { return this.firstName + " " + this.lastName; }
µ¥¶ÀµÄ this
ÔÚµ¥¶ÀʹÓÃʱ£¬ÓµÓÐÕßÊÇÈ«¾Ö¶ÔÏó£¬Òò´Ë this Ö¸µÄÊÇÈ«¾Ö¶ÔÏó¡£
ÔÚä¯ÀÀÆ÷´°¿ÚÖУ¬È«¾Ö¶ÔÏóÊÇ [object Window]£º
ʵÀý
var x = this;
ÔÚÑϸñģʽÖУ¬Èç¹ûµ¥¶ÀʹÓã¬ÄÇô this Ö¸µÄÊÇÈ«¾Ö¶ÔÏó [object Window]£º
ʵÀý
"use strict"; var x = this;
º¯ÊýÖÐµÄ this£¨Ä¬ÈÏ£©
ÔÚ JavaScript º¯ÊýÖУ¬º¯ÊýµÄÓµÓÐÕßĬÈÏ°ó¶¨ this¡£
Òò´Ë£¬ÔÚº¯ÊýÖУ¬this Ö¸µÄÊÇÈ«¾Ö¶ÔÏó [object Window]¡£
ʵÀý
function myFunction() { return this; }
º¯ÊýÖÐµÄ this£¨Ñϸñģʽ£©
JavaScript Ñϸñģʽ²»ÔÊÐíĬÈϰ󶨡£
Òò´Ë£¬ÔÚº¯ÊýÖÐʹÓÃʱ£¬ÔÚÑϸñģʽÏ£¬this ÊÇ䶨ÒåµÄ£¨undefined£©¡£
ʵÀý
"use strict"; function myFunction() { return this; }
ʼþ´¦Àí³ÌÐòÖÐµÄ this
ÔÚ HTML ʼþ´¦Àí³ÌÐòÖУ¬this Ö¸µÄÊǽÓÊÕ´ËʼþµÄ HTML ÔªËØ£º
ʵÀý
<button onclick="this.style.display='none'"> µã»÷À´É¾³ýÎÒ£¡ </button>
¶ÔÏó·½·¨°ó¶¨
ÔÚ´ËÀýÖУ¬this ÊÇ person ¶ÔÏó£¨person ¶ÔÏóÊǸú¯ÊýµÄ¡°ÓµÓÐÕß¡±£©£º
ʵÀý
var person = { firstName : "Bill", lastName : "Gates", id : 678, myFunction : function() { return this; } };
ʵÀý
var person = { firstName: "Bill", lastName : "Gates", id : 678, fullName : function() { return this.firstName + " " + this.lastName; } };
»»¾ä»°Ëµ£¬this.firstName Òâζ×Å this£¨person£©¶ÔÏóµÄ firstName ÊôÐÔ¡£
ÏÔʽº¯Êý°ó¶¨
call() ºÍ apply() ·½·¨ÊÇÔ¤¶¨ÒåµÄ JavaScript ·½·¨¡£
ËüÃǶ¼¿ÉÒÔÓÃÓÚ½«ÁíÒ»¸ö¶ÔÏó×÷Ϊ²ÎÊýµ÷ÓöÔÏó·½·¨¡£
Äú¿ÉÒÔÔÚ±¾½Ì³ÌºóÃæÔĶÁÓÐ¹Ø call() ºÍ apply() µÄ¸ü¶àÄÚÈÝ¡£
ÔÚÏÂÃæµÄÀý×ÓÖУ¬µ±Ê¹Óà person2 ×÷Ϊ²ÎÊýµ÷Óà person1.fullName ʱ£¬this ½«ÒýÓà person2£¬¼´Ê¹ËüÊÇ person1 µÄ·½·¨£º
ʵÀý
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"Bill",
lastName: "Gates",
}
person1.fullName.call(person2); // »á·µ»Ø "Bill Gates"