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

    很多人都会被JavaScript中this的指向(也就是函数在调用时的调用上下文)弄晕,这里做一下总结:


    首先,顶层的this指向全局对象。

    函数中的this按照调用方法的不同,其指向也不同:

    1、函数调用中的this指向全局对象

    2、方法调用的函数中的this指向调用函数的对象:

    function AnObject(name){
    	this.name = name;
    	this.getThis = function(){
    		console.log(this);
        }
    }
    var ob = new AnObject('test');
    ob.getThis(); //AnObject {name: "test"}
    这里方法getThis被对象ob调用,故这里的this指向ob对象{name: "test"};


    function getThis(){
        console.log(this);
    }
    getThis();  // Window
    console.log(window.getThis); //function getThis(){......}
    这里getThis是直接在顶层作用域下定义的一个方法,这里的this返回全局对象Window。我们都知道全局变量其实是作为全局对象的属性来实现的,这里的函数也是如此。用function getThis(){......}的写法等同于 var getThis = function() {......}。

    而关于”顶层的this指向全局对象“,我的个人理解是:  顶层的代码段可以理解为全局作用域下的一个匿名函数,暨全局对象的一个方法,执行完毕后就销毁。那么这个方法中的this自然指向全局对象了。在REPL或者浏览器的控制台交互中,我们都可以感受到这样的性质。


    3、构造函数中的this指向新创建的对象

    function AnObject(name) {
        this.name = name;
        console.log(this);
    }
    var ob = new AnObject('another test');// AnObject {name: "another test"}

    4、使用了apply、call、bind方法时,指向方法所指定的对象

    function AnObject(name){
    	this.name = name;
    	this.getThis = function(){
    		console.log(this);
        }
    }
    var ob = new AnObject('test');
    
    ob.getThis.call({name: ' surprise '}); //Object {name: " surprise "}
    ob.getThis.apply({name: ' surprise '});//Object {name: " surprise "}
    var a = ob.getThis.bind({name: ' surprise '});
    a();                                  //Object {name: " surprise "}
    为了化简,这里忽略了”参数列表“这个参数,仅仅传入了新的作用域。可以看到,这时this的指向是我们所指定的对象。

  • 相关阅读:
    Python yield 使用浅析
    python调试
    程序员常用的技术网站
    使用Pylint规范你的Python代码
    Python面试题整理-更新中
    2019-2020-1 1823《程序设计与数据结构》每周成绩
    2019-2020-1 1823《程序设计与数据结构》问题汇总(正在更新)
    2019-2020-1 1823《程序设计与数据结构》第二、三周作业总结
    2019-2020-1 1823《程序设计与数据结构》第一周作业总结
    2019-2020-1 1823《程序设计与数据结构》预备作业总结
  • 原文地址:https://www.cnblogs.com/zhuwq585/p/7492843.html
Copyright © 2011-2022 走看看