Primarily I'm a C# developer learning Javascript of late. I was trying out ES6 classes. I expected ES6 classes to behave like regular classes, but finding many anomalies.
class Test{
constructor(){
console.log("Constructor Invoked");
}
instanceMethod1(){
console.log("instanceMethod1 Invoked");
}
instanceMethod2InvokesInstanceMethod1(){
console.log("instanceMethod2InvokesInstanceMethod1 Invoked");
this.instanceMethod1();
//instanceMethod1(); //wont work in JS, but will work in C#
}
instanceMethod3InvokesStaticMethod1(){
console.log("instanceMethod3InvokesStaticMethod1 Invoked");
Test.staticMethod1();
//staticMethod1(); //Wont work in JS, but will work in C#
}
static staticMethod1(){
console.log("staticMethod1 Invoked");
}
static staticMethod2InvokingStaticMethod1(){
console.log("staticMethod2InvokingStaticMethod1 Invoked");
this.staticMethod1();
Test.staticMethod1();
//staticMethod1(); //Wont work in JS, but will work in C#
}
static staticMethod3InvokingInstanceMethod1(){
console.log("staticMethod3InvokingInstanceMethod1 Invoked");
new Test().instanceMethod1();
//this.instanceMethod1(); //wont work
}
}
var ob = new Test();
ob.instanceMethod1();
ob.instanceMethod2InvokesInstanceMethod1();
ob.instanceMethod3InvokesStaticMethod1();
Test.staticMethod1();
Test.staticMethod2InvokingStaticMethod1();
Test.staticMethod3InvokingInstanceMethod1();
My Questions:
- Inside
instanceMethod2InvokesInstanceMethod1
- Why callinginstanceMethod1()
wont work? Instance methods can't be invoked without an instance and hence calling an instance method within an instance method should make sense right? - Inside
instanceMethod3InvokesStaticMethod1
-Test.staticMethod1()
will work is fair enough. But why cant we directly callstaticMethod1
? - Inside
staticMethod2InvokingStaticMethod1
- Howthis.staticMethod1()
works ? What is thethis
object here ? - Inside a static method,
this.staticMethod1()
works, but notthis.instanceMethod1()
. Why ? I guess answer to question 3, should help answer this question.
Could someone please help me here.