javascript - this question
仅有的幸福
仅有的幸福 2017-05-19 10:23:39
0
5
406

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();
仅有的幸福
仅有的幸福

reply all(5)
小葫芦

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

小葫芦
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);
曾经蜡笔没有小新

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

给我你的怀抱

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

Ty80

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();

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!