search

Home  >  Q&A  >  body text

javascript - Problems pointed to by this

function Persion(name) {
    var self = this;
    self.name = name;
    console.log(self);
    console.log(this);
}

Persion.prototype = {
    before: function() {
        // var self = this;
        console.log('before' + self);
        console.log('before' + this);

        return this;
    },

    after: function(){
        // var self = this;
        console.log('after' + self);
        console.log('after' + this);

        return this;
    }
};


var a = new Persion('Tom');
a.before().after();

When var a = new Persion('Tom'), self and this still point to Persion. When executing a.before().after(), self points to Window. I want to use self to save this. , I did not artificially change self, so why does the value of self change? What is the principle?

Supplement:
is the top sentence var self= this; during debugging, I found that self changed from Persion to window. I commented out the declarations in before and after and found that when self was not declared, the output was not undefined but It’s window

ringa_leeringa_lee2823 days ago539

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-05-19 10:10:29

    The self variable is not defined in the before function, so self here refers to window.self. The
    self property returns a read-only reference to the window itself. Equivalent to the Window property.

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:10:29

    The value of _self in your before and after is undefined

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:10:29

    I understand that there is a problem. My problem is extracted from my code and simplified. The original code has an asynchronous part, and this becomes window in the asynchronous part. When debugging, I found that the self in the top sentence var self= this changed from Persion to window, so I thought there was something wrong with self.

    reply
    0
  • Cancelreply