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

    JavaScript

    this 关键字

    什么是 this

    • JavaScript中的 this 关键字指的是它所属的对象

    • 拥有不同的值,具体取决于使用this关键字的位置

      在方法中,this指的是(方法)所有者的对象

      在单独的情况下,this指的是全局对象

      在函数中,this指的是全局对象(严格模式:undefined)

      在事件中,this指的是接收事件的对象

    方法中的 this

    fullName : function() {
        return this.firstName + " " + this.lastName ;
    }
    

    单独的 this

    • 单独使用时,this指的是全局对象;在浏览器窗口中,全局对象是 object Window

    函数中的 this(默认)

    function myFunction() {
        return this;
    }
    

    事件处理程序中的 this

    • 在HTML事件处理程序中,this 指的是接收此事件的HTML元素
    <button onclick = "this.style.display = 'none' ">
        点击删除;
    </button>
    

    对象方法绑定

    var person = {
        firstName : "Mirror",
        lastName  : "China",
        id 		  : 10086,
        fullName  : function() {
            return this.firstName + " " + this.lastName ;
        }
    };
    

    this.firstName 意味着 this person 对象中的 firstName和lastName属性

    显式函数 绑定

    • call() 和 apply() 方法是预定义的JavaScript方法;可以用于将另一个对象作为参数调用对象方法
    var person1 = {
        fullName : function() {
            return this.firstName + " " + this.lastName ;
        }
    };
    var person2 = {
        firstName : "Mirror" ,
        lastName  : "China" ,
    };
    person1.fullName.call(person2) ; // person2将会作为参数供person1调用
    
  • 相关阅读:
    3503: [Cqoi2014]和谐矩阵
    2734: [HNOI2012]集合选数
    P3900 [湖南集训]图样图森破
    4557: [JLoi2016]侦察守卫
    牛客OI周赛6-提高组 B 践踏
    连续区间的最大公约数
    Wannafly挑战赛5 D. 子序列
    牛客国庆集训派对Day1 B. Attack on Titan
    4538: [Hnoi2016]网络
    [SHOI2015]超能粒子炮·改
  • 原文地址:https://www.cnblogs.com/wangyuyang1016/p/11081025.html
Copyright © 2011-2022 走看看