简体   繁体   中英

Why isnt “this” work with console.log as an argument?

I assumed that .call should //change the context of this in the log method to obj, but it doesnt seem to be //doing that, it seems to refer to the window object as if I used this side a function

let obj={
    a: "this should work right?"
}

console.log.call(obj,this.a);//returns undefined

you are not in a function scope, instead you should test this way:

let obj={
    a: "this should work right?"
};

let myFunc = function() { // u define a function scope here
    return this.a;
};

console.log(myFunc.call(obj));
// console.log.call(obj,this.a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM