1 <!-- 2 英语单词:checkout:收银台 refresh:刷新 3 const Index = () => import(‘/page/index.vue‘)//等于const Index = function a(){return import(‘/page/index.vue‘)} 4 ?5 js高级之this是谁? 6 this本质上就是调用了就指向谁,this在指向谁有以下4种情况: 7 -------------------------------------------------------------------------------------- 8 *this之普通函数: 9 ?function t(){10 ????this.age=23;11 ??}12 ??t();//如果没有这方法就会报undefined,在window就找不到age13 ??//这个调用者是null,this为null时,js把this指向window14 ??//在es5及以后,当this为null时抛出异常15 ??alert(window.age);16 ??//函数内带有this操作,不能直接调用,应该new,否则会污染全局17 -------------------------------------------------------------------------------------18 *this之对象方法19 ?window.name=‘kjx‘20 ??function intro() {21 ????alert(‘my name is ‘+this.name);22 ??}23 ??var dog={24 ????name:‘孙小二‘,25 ??}26 ??dog.intro=intro;27 ??dog.intro();//输出是my name is 孙小二28 ??var cat={29 ????name:‘加肥猫‘30 ??}31 ??cat.intro=intro;32 ??cat.intro();//输出是my name is 加肥猫33 ??(cat,intro=dog.intro)();//输出是全局变量my name is kjx,如果没有定义全局变量的话就会没有输出,赋值运算的结果是一个值,如果你拿一个值来调用这个值不属于任何一个对象34 --------------------------------------------------------------------------------------35 *this之构造函数:36 var a = new fn();37 ??console.log(a);38 ??function cat (name,color) {39 ????this.name=name;40 ????this.color=color;41 ??}42 43 ??/*44 ??0.方法new的瞬间,得到一个空对象{}45 ??1.方法的this指向该空对象46 ??2.运行方法47 ????{}.name=name48 ????{}.color=color49 ????返回该对象50 ??*/51 ??var cat=new cat();//会得到一个新的对象,方法内的this指向该新对象52 ??console.log(cat);53 --------------------------------------------------------------------------------------
1 <style> 2 ??div{ 3 ????height: 300px; 4 ????width: 300px; 5 ????margin: 10px; 6 ????border: 1px solid blue; 7 ??} 8 </style> 9 <body>10 <!--11 *this之通过call,apply调用,call和apply会动态更改this的指向12 -->13 <div id="test1">test1</div>14 <div id="test2">test2</div>15 </body>16 <script>17 ??var test1=document.getElementById(‘test1‘)18 ??var test2=document.getElementById(‘test2‘)19 ??function t () {20 ????this.style.background=‘gray‘;21 ??}22 ??t.call(test2);23 ??/*24 ??函数名.call(对象,参数1,参数2,参数3,...)25 ??1.把函数的this,指向对象26 ??2.运行函数,传参为参数1,参数2,参数3....)27 ??函数名.apply(对象,[参数1,参数2,参数3,...])28 ??1.把函数的this,指向对象29 ??2.运行函数,传参为参数1,参数2,参数3....)30 ??*/31 32 </script>
1 //课后习题: 2 ??var name="The Window"; 3 ??var object={ 4 ????name:‘My Object‘, 5 ????getNameFunc:function () { 6 ??????return function () { 7 ????????return this.name; 8 ??????} 9 ????}10 ??}11 ??alert(object.getNameFunc()());//输出的是The Window,为什么呢? function () { return this.name; }相当于object.getNameFunc(),return返回的是函数函数是一个值,this.name就是全局变量的name
JS高级之this是谁?
原文地址:https://www.cnblogs.com/junxiaobai/p/10508116.html