zoukankan      html  css  js  c++  java
  • 详解js中的this指向

    this指向问题是个老生常谈的问题了,现在我给大家一个例子

    var obj={
      bar:'Cynthia' ,
       foo:function(){
        console.log(this.bar,"wahahah")
        }
    }
    
    var foo=obj.foo;
    foo(); // 0 "wahahah" 
    obj.foo(); // Cynthia wahahah

    虽然obj.foo和foo指向同一个函数,但是执行结果却不一样。

    造成这种差异的原因,就在于函数体内部使用了this关键字。很多教材里面会告诉你,this指向的是其运行时所在的环境。但是光看这句话是不是有点懵

    下面我把this的指向都列给大家

    浏览器

    非严格模式下

    function add(x,y){
        console.log(this); // window
        return x+y;
    }
    add(1,40);

    在非严格模式下的时候,this的运行环境所在的环境是windows,所以返回的是window

    严格模式下

    function add(x,y){
        'use strict'
        console.log(this); // undefined
        return x+y;
    }
    add(1,40);

    JavaScript高级程序设计中有这样一句话:在严格模式下,未指定环境对象而调用函数,则this值不会转为window。除非明确把函数添加到某个对象或者调用appy()call(),否则this值将是undefined

    看是否绑定了new

    如果绑定了new的话,并且构造函数没有返回function或object,那么this指向这个新对象

    function Person(name,age){
        this.name=name;
        this.age=age;
        this.sayHi=function(){
        console.log(this.age)
    }
    }
    let person=new Person("那抓",6);
    person.sayHi();// 6

    构造函数返回值是function或者object,返回的是构造函数返回的对象

    function Super(age){
        this.age=age;
        let obj={a:'2'};
        return obj;
    }
    let instance=new Super(30);
    console.log(instance);// {a:2}
    console.log(instance.age);// undefined

    箭头函数

    箭头函数没有自己的this,继承外层上下文绑定的this

    let obj={
        age:20,
        info:function(){
        return ()=>{
            console.log(this,this.age); // this继承的是外层上下文绑定的this
            }
        }
    }
    let person={age:30};
    let info=obj.info();
    info(); // 指向的是obj
    let info2=obj.info.call(person);
    info2();

    node环境中

    node环境中无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this都指向空对象{}

  • 相关阅读:
    [模板] 循环数组的最大子段和
    [最短路][几何][牛客] [国庆集训派对1]-L-New Game
    [洛谷] P1866 编号
    1115 Counting Nodes in a BST (30 分)
    1106 Lowest Price in Supply Chain (25 分)
    1094 The Largest Generation (25 分)
    1090 Highest Price in Supply Chain (25 分)
    树的遍历
    1086 Tree Traversals Again (25 分)
    1079 Total Sales of Supply Chain (25 分 树
  • 原文地址:https://www.cnblogs.com/cythia/p/11363830.html
Copyright © 2011-2022 走看看