1. this 的指向问题
    2. 1.不管函数或者方法是如何声明的,要看这个函数或者方法最终是谁调用
    3. 2.谁最终调用这个函数或方法,那么这个函数或者方法的this就指向谁

    1.普通函数中的this,指向window
    在全局作用域内定义的变量和函数其实都是window的属性和方法 window是浏览器的顶级对象,在使用的时候可以忽略

    1. function foo(){
    2. console.log(1323);
    3. console.log(this);
    4. }
    5. foo();
    6. window.foo()

    2.事件处理程序中的this,指向正在触发事件的事件源,但是也有例外

    1. var btn =document.getElementById('btn')
    2. btn.onclice=function(){
    3. console.log(this) //这个this 就是指向btn(当前正在执行事件处理程序的事件源)
    4. }
    5. btn.addEventListener('click',function(){
    6. console.log(this);//指代当前正在执行事件处理程序的事件源
    7. })
    8. // 例外
    9. btn.attachEvent("onclick",function(){
    10. console.log(this) //指代 window
    11. })

    3.构造函数当中 this始终指向创建出来的实例,构造函数的原型对象中的this和构造函数的this一样

    1. function Stu(name,age,sex){
    2. this.name =name;
    3. this.age =age;
    4. this.sex=sex;
    5. }
    6. Stu.prototype.say=function(){
    7. console.log(this.name) //都是指向这个zs这个实例对象
    8. }
    9. var zs =new Stu("张三",15,"男")
    10. //拓展
    11. //普通实例对象中的this指向对象本省,同时他没有prototype的属性
    12. var obj={
    13. name:'jack',
    14. age:18,
    15. sayHi:function(){
    16. console.log(this.name)
    17. }
    18. }
    19. obj.prototype.sayHello=function(){ //boj这个实例对象没有prototype
    20. console.log(this.name)
    21. }
    22. console.dir(obj)

    4.定时器的指向是指向window

    1. setTimeout(function(){
    2. console.log(this)
    3. },1000)
    4. setInterval(function(){console.log(123,this)},1000)
    5. setTimeout(()=>{
    6. console.log(this)
    7. },1000) //也是指向window

    拓展

    1. function Stu(name,age){
    2. this.name =name;
    3. this.age =age;
    4. }
    5. Stu.prototype.sayHi=function(){
    6. console.log(this.name)
    7. }
    8. Stu.prototype.sayHello =function(){
    9. console.log(this.age)
    10. }
    11. //区别:上面和下面等待区别就是上面有constructor,下面没有constructor,相当于重新赋值一个普通实例对象
    12. Stu.prototype={
    13. sayHi:funtion(){console.log(this.name)},
    14. sayHello:function(){console.log(this.age)}
    15. }
    16. var zs= new Stu('张三',16)

    案例一:

    1. function foo(){
    2. console.log(this);//指向window
    3. console.log(this.name)
    4. }
    5. var name = '张三';
    6. var obj ={
    7. name:'前端工程师',
    8. sayHi:function(){
    9. console.log(this);
    10. console.log(this.name);
    11. }
    12. }
    13. obj.sayHi();//此时这个this就是指向了 obj 这个对象
    14. foo=obj.sayHi;
    15. foo();//这是这里面的this指向window