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调用
    
  • 相关阅读:
    (四)STL中的算法
    (三)openssl库实现对称和非对称加密
    (十一)etcd项目
    (十二)插件之dlopen/dlsym/dlclose 加载动态链接库
    (十一)访问权限关键字publi/private/protected
    RESTful架构
    (零)TCP/IP详解综述
    (二)辗转相除法求最大公约数
    (一)简单的TcpServer
    SpringMVC异常处理
  • 原文地址:https://www.cnblogs.com/wangyuyang1016/p/11081025.html
Copyright © 2011-2022 走看看