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
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.