• jave script 中this的指向 (六种场景)


    第一个场景:

      在普通函数调用时,this指向window

    function test(){

        this.a = 1;
        alert(this.a);
      }
      test(); // 1
     this 代表的是window
     
    场景二:
      在对象的方法调用时,this指向方法所属的对象
    function test(){
      alert(this.age);
    }
    var obj = {};
    obj.age = 1;
    obj.m = test;
    obj.m(); // 1
    this 代表的是obj;

    场景三:
    构造函数调用时,this指向当前所创建的对象。
     function test(){
        this.a = 1;
        }   var obj = new test();   alert(obj.a); // 1
       // this 代表new出来的对象obj   var a = 2;   function test(){     this.a = 1;   }   var obj = new test();   alert(a); //2
    //这里的this代表的是window 所以alert(a)弹出2;


    场景四:
      在定时器中,this指向window

    setInterval(window.fn,1000);

       setInterval(function(){

       console.log(Math.random());

       console.log(this);

     },1000);

    this代表的是window 

    场景五:
      在事件绑定的方法中,this指向事件源
        

    // id为box的div元素对象

    var box = document.getElementById('box');

    // 为box注册事件

    box.onclick = function () {

      console.log(this);

    };

    场景六 :(在bind 、call、apply 中)

      1..apply() 调用 ,apply方法作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数

      

     var x = 0;
      function test(){
        alert(this.x);
      }
      var o={};
      o.x = 1;
      o.m = test;
      o.m.apply(); //0
    //apply()的参数为undefind 和null 时,默认是全局对象,所以这里的this指向全局对象
    
      o.m.apply(o); //1

      2:call() call方法和apply是一样的用法,唯一不同的是,函数或方法被调用时,call是用数组来存放实参。

    var obj = {
      0: 100,
      1: 200,
      2: 300,
      3: 400,
      length: 4
    }
    // obj.push(500); // 报错 对象中不存在这个方法
    // 借用数组的
    Array.prototype.push.call(obj,500);
    console.log(obj);  //{0: 100, 1: 200, 2: 300, 3: 400, 4: 500, length: 5}

        3:bind()   和call使用方式一样,不一样的时,使用bind时,借用的函数不会被立即执行,而是返回一个新的函数,若要执行,需要自己调用。

           var obj = { name: '调用者', age: 123 };

          setInterval(function () {
            console.log(this);  //{name: "调用者", age: 123} (过5秒打印一次)
          }.bind(obj), 1000);

        

    以上是我总结的this场景中的指向问题。

  • 相关阅读:
    css3圆环百分比,菜单栏定位导航
    Css中的两个重要概念:块状元素和内联元素
    前端进阶试题(css部分)
    HTML5移动开发学习笔记之CSS3基础学习
    HTML5移动开发学习笔记之Canvas基础
    js加载从0到80变化过程代码,让其4s中加载完毕
    我了解到的JavaScript异步编程
    原生JS+Canvas实现五子棋游戏
    Web缓存相关知识整理
    百度前端技术学院2017学习总结
  • 原文地址:https://www.cnblogs.com/suriz/p/9566643.html
Copyright © 2020-2023  润新知