The 'this' keyword behaves differently in Nodejs and browser

前端 未结 6 1858
栀梦
栀梦 2020-12-01 10:36

I have this piece of code :

var obj1;
var obj2;

function x() {
    obj1 = this;
}

function y() {
    obj2 = this;
}

x();
y();

console.log(obj1 === o         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 11:24

    I have no Node.js server in a hand right now, but I think you can yourself research this question, and give answer for us :D see code below

    Try to run:

    console.log(this.constructor.name+" "+obj1.constructor.name+" "+obj2.constructor.name);

    And also you can debug "Parent Class" name in a function:

    function x() {
        console.log("x this: "+this.constructor.name);
        obj1 = this;
    }
    
    function y() {
        console.log("y this: "+this.constructor.name);
        obj2 = this;
    }
    

    And for view Object methods / properties you can use something like this:

    for (a in obj2) {
        console.log("obj2." + a + " = " + obj2[a]);
    }
    

提交回复
热议问题