JavaScript中this是做什么用的? 水深无声 2022-02-14 08:01 244阅读 0赞 ##### this(上下文对象) ##### * 我们每次调用函数时,解析器都会将一个上下文对象作为隐含的参数传递进函数。 使用this来引用上下文对象,根据函数的调用形式不同,this的值也不同。 * this的不同的情况: 1. 以函数的形式调用时,this是window var aOne = '我是Windows对象的一个变量' function initTest() { var aTwo = 'initTest的变量two'; var aThree = 'initTest的变量three'; console.log(this); } console.log(this) initTest(); ![在这里插入图片描述][20190426090253302.png_pic_center] ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MDQzOTIz_size_16_color_FFFFFF_t_70_pic_center] 以上控制台输出可以看出`this`代表的是`Windows`可以使用Windows的属性 1. 以方法的形式调用时,this就是调用方法的对象 var aOne = '我是Windows对象的一个变量' var InitTest = { atwo: 'initTest的变量two', athree: 'initTest的变量three', afour: function () { console.log(this)//这里就是指向 InitTest 方法 } } console.log(this)//这里还是 Windows InitTest.afour() ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MDQzOTIz_size_16_color_FFFFFF_t_70_pic_center 1] ![在这里插入图片描述][20190426092525841.png_pic_center] 1. 以构造函数的形式调用时,this就是新创建的对象 /* * 创建一个InitTest构造函数 * 在Person构造函数中,为每一个对象都添加了一个afour方法, */ function InitTest() { this.atwo='initTest的变量two'; this.aThree='initTest的变量three'; this.afour=function(){ console.log(this) } console.log(this) } var InitTest= new InitTest() //this->InitTest InitTest.afour()//this->InitTest console.log(this)//this->Windows ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MDQzOTIz_size_16_color_FFFFFF_t_70_pic_center 2] [20190426090253302.png_pic_center]: /images/20220214/98a6d6d28c6d4d7489f9c86a4363803a.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MDQzOTIz_size_16_color_FFFFFF_t_70_pic_center]: /images/20220214/38b418b61a0a4be1b5f63d6f9d01f455.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MDQzOTIz_size_16_color_FFFFFF_t_70_pic_center 1]: /images/20220214/7551598b781d430e9ca034c54a940c1f.png [20190426092525841.png_pic_center]: /images/20220214/c22b4779847b4589b3f33a016806c690.png [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MDQzOTIz_size_16_color_FFFFFF_t_70_pic_center 2]: /images/20220214/7d876b70784a40afb7d19f9de92ad48d.png
还没有评论,来说两句吧...