this

作者: Liberty寒风 | 来源:发表于2017-07-02 10:55 被阅读0次

    Node脚本中global和this是区别对待的,而Node命令行中,两者可等效为同一对象

    函数正常被调用(不带new)时,里面的this指向的是全局作用域

    foo = 'bar';
    function testThis() {
      this.foo = "foo";
    }
    console.log(this.foo); //logs "bar"
    testThis();
    console.log(this.foo); //logs "foo"
    

    还有个例外,就是使用了"use strict";。此时this是undefined。

    foo = "bar";
    function testThis() {
      "use strict";
      this.foo = "foo";
    }
    console.log(this.foo); //logs "bar"
    testThis();  //Uncaught TypeError: Cannot set property 'foo' of undefined 
    

    在JavaScript中,函数可以嵌套函数,也就是你可以在函数里面继续定义函数。但内层函数是通过闭包获取外层函数里定义的变量值的,而不是直接继承this。

    function Thing() {
    }
    Thing.prototype.foo = "bar";
    Thing.prototype.logFoo = function () {
        var info = "attempting to log this.foo:";
        function doIt() {
            console.log(info, this.foo);
        }
        doIt();
    }
    
    var thing = new Thing();
    thing.logFoo();  //logs "attempting to log this.foo: undefined"
    

    将实例的方法作为参数传递,可以将方法理解为堆中的区域,变量为指向该区域的指针,当a.c -> b,d.e = a.c,变成了d.e ->b,你确定以前的this还是那个this吗?记住,对象间的赋值是引用。

    function Thing() {
    }
    Thing.prototype.foo = "bar";
    Thing.prototype.logFoo = function () {  
        console.log(this.foo);   
    }
    
    function doIt(method) {
        method();
    }
    
    var thing = new Thing();
    thing.logFoo(); //logs "bar"
    doIt(thing.logFoo); //logs undefined
    

    相关文章

      网友评论

          本文标题:this

          本文链接:https://www.haomeiwen.com/subject/ytyncxtx.html