I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo:
function Note() {
var self = this;
var note = document.createElement(\'d
The variable is captured by the inline functions defined in the method. this
in the function will refer to another object. This way, you can make the function hold a reference to the this
in the outer scope.
Actually self is a reference to window (window.self
) therefore when you say var self = 'something'
you override a window reference to itself - because self exist in window object.
This is why most developers prefer var that = this
over var self = this;
Anyway; var that = this;
is not in line with the good practice ... presuming that your code will be revised / modified later by other developers you should use the most common programming standards in respect with developer community
Therefore you should use something like var oldThis
/ var oThis
/ etc - to be clear in your scope // ..is not that much but will save few seconds and few brain cycles
Yes, you'll see it everywhere. It's often that = this;
.
See how self
is used inside functions called by events? Those would have their own context, so self
is used to hold the this
that came into Note()
.
The reason self
is still available to the functions, even though they can only execute after the Note()
function has finished executing, is that inner functions get the context of the outer function due to closure.
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.getfullname = function () {
return `${this.firstname} ${this.lastname}`;
};
let that = this;
this.sayHi = function() {
console.log(`i am this , ${this.firstname}`);
console.log(`i am that , ${that.firstname}`);
};
}
let thisss = new Person('thatbetty', 'thatzhao');
let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};
thisss.sayHi.call(thatt);