zoukankan      html  css  js  c++  java
  • JavaScript this 关键字

    JavaScript this 关键字

    面向对象语言中 this 表示当前对象的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

    • 在方法中,this 表示该方法所属的对象。
    • 如果单独使用,this 表示全局对象。
    • 在定时函数中,this 表示全局对象。
    • 在函数中,在严格模式下,this 是未定义的(undefined)。
    • 在事件中,this 表示接收事件的元素。
    • ES6箭头函数:函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。箭头函数的最大作用就是this指向
    • 改变this指向方法: call() 和 apply() 方法可以将 this 引用到任何对象。
    例如在对象中this代表该对象,下面的例子中指向person
    // 创建一个对象
    var person = {
      firstName: "李",
      lastName : "四",
      id     : 5566,
      fullName : function() {
        return this.firstName + " " + this.lastName;
      }
    };
    // 显示对象的数据
    document.write(person.fullName()) //李四
    单独使用this时代表全局变量
    var x = this;
    console.log(x)  //window
    函数中使用this,默认函数的所属着,此时的this代表myFunction()
    function myFunction() {
      return this;     
    }
    函数在严格模式下使用this,这时候 this 是 undefined。
    "use strict";
    function myFunction() {
      return this;
    }
    document.write(myFunction())  //undefined
    事件中的 this

    在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素:

    <button onclick="this.style.display='none'">点我后我就消失了</button>   //button按钮消失
    显式函数绑定

    在 JavaScript 中函数也是对象,对象则有方法,apply 和 call 就是函数对象的方法。这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。
    在下面实例中,当我们使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法:

    var person1 = {
      fullName: function() {
        return this.firstName + " " + this.lastName;
      }
    }
    var person2 = {
      firstName:"张",
      lastName: "三",
    }
    var x = person1.fullName.call(person2); 
    document.write(x);  //张三

    定时器中的this指向window

    var name = 'window';
    var obj = {
        name: 'obj',
        fn: function () {
            var timer = null;
            clearInterval(timer);
            timer = setInterval(function () {
                console.log(this.name);   //window
            }, 1000)
        }
    请用今天的努力,让明天没有遗憾。
  • 相关阅读:
    requests实现接口自动化(三)
    api 25 PopupWindow会占据整个屏幕
    INSTALL_FAILED_USER_RESTRICTED
    事件分发_水平滑动和垂直冲突解决
    MPAndroidChart market右边显示不全问题
    SimpleDateFormat 取当前周的周一和周日的日期,当前月第一个和最后一天的日期
    Callable,Runnable比较及用法
    Android系统启动流程
    debug-stripped.ap_' specified for property 'resourceFile' does not exist
    Theme.AppCompat.Light的解决方法
  • 原文地址:https://www.cnblogs.com/cupid10/p/15617798.html
Copyright © 2011-2022 走看看