javascript - Problems pointed to by this
ringa_lee
ringa_lee 2017-05-19 10:08:29
0
3
515
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_lee
ringa_lee

ringa_lee

reply all(3)
左手右手慢动作

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.

黄舟

The value of _self in your before and after is undefined

巴扎黑

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template