Please check this code. How anotherFunc
is able to read this
values of outerFunc
, where both functions are having different scopes?
console.log("hello");
function outerFunc() {
this.name = "Krishna";
this.mobile = 12345;
this.address = "India";
function innerFunc() {
console.log(this.name); // "krishna"
console.log(this.mobile); // 12345
console.log(this.address); // "India"
}
innerFunc();
}
outerFunc();
function anotherFunc() {
console.log(this.name); // 'Krishna'
console.log(this.mobile); // 12345
console.log(this.address); //'India'
}
anotherFunc();
Update:
console.log("hello");
function outerFunc() {
this.name = "Krishna";
this.mobile = 12345;
this.address = "India";
this.innerFunc = function () {
console.log(this.name);
console.log(this.mobile);
console.log(this.address);
};
}
let func = new outerFunc();
func.innerFunc();
function anotherFunc() {
console.log(this.name); // 'Krishna'
console.log(this.mobile); // undefined
console.log(this.address); // undefined
}
anotherFunc();