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();
高洛峰2017-05-19 10:25:39
The final object ambition is window, window.scope, and what is returned is undefined
高洛峰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);
曾经蜡笔没有小新2017-05-19 10:25:39
this pointing problem
this pointing in different execution environments of JS functions
给我你的怀抱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
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();