Last active
April 28, 2020 09:58
-
-
Save ishwarrimal/fac75dccfb734327fa85a03d38162764 to your computer and use it in GitHub Desktop.
Confusions with this variable's context which arise with constructor invocation pattern for regular and arrow function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function GetValue1(){ | |
this.value = 10; | |
// using regular funciton to access the varialbe `this.value` | |
var printValue = function(){ | |
// Since printValue is an independent funciton and not a property of the GetValue1 constructor, | |
// so when this is called as constructor, printValue points to globalScopr | |
// where in case of reguar funciton call, this will bound to the execution context of GetValue1 | |
console.log('The value of this.value is, ', this.value) //consoles 20 | |
} | |
printValue() | |
} | |
function GetValue2(){ | |
this.value = 10; | |
// using arrow function to access `this.value` | |
var printValue = () => { | |
// Arrow function in any case will have context of its enclosing block | |
console.log('The value of this.value is, ', this.value) | |
} | |
printValue() | |
} | |
var value = 20 | |
//acessing GetValue1 as a constructor | |
var x = new GetValue1() | |
//calling GetValue1 as a regular function | |
GetValue1() | |
// accessing GetValue2 as a constructor | |
new GetValue2() | |
console.log(x) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function foo(){ | |
console.log("foo.a =", foo.a) | |
console.log("this.a =", this.a) | |
} | |
var foo1 = () => { | |
console.log("foo1.b =", foo1.b) | |
console.log("this.b =", this.b) | |
} | |
foo.a = 20 | |
var a = 10 | |
foo() | |
//foo.a =20 | |
//this.a =10 | |
new foo() | |
//foo.a =20 | |
//this.a =undefined | |
foo1.b = 30 | |
var b = 40 | |
foo1() | |
// foo1.b =30 | |
// this.b =40 | |
new foo1() | |
// error: Uncaught TypeError: foo1 is not a constructor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment