Home  >  Q&A  >  body text

javascript - this question

Why is undefined printed? How can I make this code print global, obj and inner respectively

var scope = 'global';

function log() {
    console.log(this.scope)
}

var obj = {
    scope: 'obj',
    do: function () {
        var scope = 'inner';
        log()
    }
};

obj.do();
仅有的幸福仅有的幸福2711 days ago418

reply all(5)I'll reply

  • 高洛峰

    高洛峰2017-05-19 10:25:39

    The final object ambition is window, window.scope, and what is returned is undefined

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:25:39

    var scope = 'global';
    
    function log() {
        console.log(this.scope)
    }
    
    var obj = {
        scope: 'obj',
        do: function () {
            var scope = 'inner';
            log();
            console.log(scope);
        }
    };
    obj.do();
    console.log(obj.scope);

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:25:39

    this pointing problem
    this pointing in different execution environments of JS functions

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:25:39

    First of all, what this code prints should be global, not undefined. Then, it is impossible to call inner through this.scope the way you write it. For the rest, just look at the this pointer

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:25:39

    var scope = 'global';

    function log() {

    console.log(this.scope)

    }

    var obj = {

    scope: 'obj',
    do: function () {
        var scope = 'inner';
        log();   //gobal
        console.log(this.scope);  //this指向obj,obj作用域中找到scope:obj
        console.log(scope);    //局部的inner
    }

    };

    obj.do();

    reply
    0
  • Cancelreply