• JS中的this关键字


    this关键字

    JS中的this代表的是当前行为执行的主体:JS中的context代表的是当前行为执行的环境(区域)

    this是谁和函数在哪定义的和在哪执行的都没有任何的关系,这和它的执行主体有关。

    如何区分this

    • 函数执行,首先看函数名前面是否有“.”,有的话,“.”前面是谁this就是谁, 没有的话this就是window
    function fn(){
        console.log(this);
    }
    var obj = {fn :fn};
    fn(); // window
    obj.fn(); // obj
    function sum(){
        fn():
    }
    sum(); // window
    
    var oo = {
        sum: function(){
            fn();
        }
    }
    oo.sum(); // window
    
    • 自执行函数中的this永远是window
    • 给元素的某一个事件绑定方法,当事件触发的时候,执行对应的方法,方法中的this是当前的元素
    function fn(){
        console.log(fn)
    }
    document.getElementById('div1').onclick = fn; // #div1
    document.getElementById('div2').onclick = function(){
        // #div2
        fn();  // window
    }
    
    • 使用 new, 在构造函数模式中,类中(函数体中),this.xxx = xxx是当前类的实例
    function CreateJsPerson(name, age){
        this.name = name;
        this.age = age;
        this.writeJS = function(){
            console.log("my name is " + this.name + ", i can                write js ~~")
        }
        console.log(this)
    }
    
    var p1 = new CreateJsPerson("lemon1", 21)
    // Object { name: "lemon1", age: 21, writeJS: writeJS() }
    
  • 相关阅读:
    Git fetch和git pull的区别
    gitlab数据迁移
    阿里云CentOS7挂载SSD云盘的方法
    phpQuery的用法
    用shell查找某目录下的最大文件
    gearman 简介
    学习笔记(3)——实验室集群WMS服务配置
    学习笔记(2)——实验室集群LVS配置
    Fedora16的双显卡切换问题
    学习笔记(1)——实验室集群配置
  • 原文地址:https://www.cnblogs.com/xiaoxu-xmy/p/13640317.html
Copyright © 2020-2023  润新知