zoukankan      html  css  js  c++  java
  • this的使用情况

    this的几种使用情况

    1、在普通函数内部,this指向的是window,在严格模式下,this的值是undefined

    function fun(){
        console.log(this);
    }
    fun();//Window
    'use strict';
    function fun(){
        console.log(this);
    }
    fun();//undefined

     

    2、在方法内部,this指向的是方法的拥有者

    var user = {
        name:'张三',
        introduce:function(){
            console.log(this.name);
        }
    }
    user.introduce();//张三

    上面的案例,this在introduce方法内部,introduce方法的拥有者是user,所以this指向user。

    3、箭头函数内部的this指向的是,创建箭头函数时所在环境中this的值

    var arrow = ()=>{
        console.log(this);
    }
    arrow();//Window

    上面案例中,创建箭头函数时arrow所在的环境是全局环境,所以this指向window

    var Car = {
        name:'奔驰',
        run:function(){
            var arrow = () =>{
                console.log(this);
            }
            arrow();//{name: "奔驰", run: ƒ}
        }
    };
    Car.run();

    上面案例中,创建箭头函数时arrow所在的环境是run方法内,在run方法内部,this指向的是run方法的拥有者Car,所以this指向Car

    4、在函数调用时使用了call、apply、bind函数后,this指向的是第一个参数

    var fun = function(){
        console.log(this);
    }
    fun.call(1);//Number {1}

    上面案例中,本来this的指向是window,但是调用了call,this指向就是第一个参数。

    5、在原型对象中的方法内,this指向的是实例化的对象

    function Person(name){
        this.name = name;
    }
    Person.prototype.introduce
    = function(){ console.log(this); }
    var xiaoming = new Person('小明'); xiaoming.introduce(); //Person {name: "小明"}

    上面案例中,Person的原型对象方法是introduce,introduce内的this指向的是实例化对象xioaming

    注:this的值必须是在函数运行时才能确定下来

    var username = '张三';
    var obj = {
        username:'李四',
        introduce:function(){
            console.log(this.username);
        }
    }
    var intro = obj.introduce;
    obj.introduce(); //李四
    intro();         //张三

    上面案例中,intro()和obj.introduce()用的是同一个函数。我们先来看 obj.introduce(),调用的obj内部方法introduce,此时方法里的this指向的是obj,所以this.username是李四。 我们在来看intro();intro声明环境是全局,所以它是一个普通函数,在普通函数内部的this指向window,所以此时this.username是张三。

    上述案例中,obj.introduce()和intro()虽然用的是同一个this,但是this的指向却不同。所以this的值只有在函数运行时才能确定下来。

  • 相关阅读:
    没想到吧?这货比 open 更适合读取文件
    卸载 PyCharm!这才是 Python 小白的最理想的 IDE
    git 会保留所有的提交吗?不会!
    C# 在构造函数内调用虚方法
    【转】第一个汇编器是怎么实现的
    SQL Server查询数据库所有表名与表说明
    Vue实现节流,防止重复提交
    mysql 查询json数组(一)
    VScode怎么在代码折叠后,插入新的内容
    Vue 通过调用百度API获取地理位置-经度纬度省份城市
  • 原文地址:https://www.cnblogs.com/MaShuai666/p/8492937.html
Copyright © 2011-2022 走看看