Here is my code snippet:
class MyClass {
name = "MyClass";
// traditional method definition
getName1(){
return this.name;
}
// method defined as an arrow function
getName2 = () => {
return this.name;
}
// traditional method definition using a this parameter
getName3(this: MyClass){
return this.name;
}
}
const c = new MyClass();
const obj = {
name: "obj",
getName1: c.getName1,
getName2: c.getName2,
getName3: c.getName3
};
const g = c.getName3;
console.log(c.getName1());
// "MyClass" because this is called in the context of c
// using a traditional method definition getName1
console.log(c.getName2());
// "MyClass" because this is called in the context of c
// using an arrow function getName2
console.log(c.getName3());
// "MyClass" because this is called in the context of c
// using a traditional method definition getName3, having
// a this parameter that statically enforce the context of c
console.log(obj.getName1());
// "obj" because this is called in the context of obj
// using the MyClass traditional method definition getName1()
// and assigning it to obj's getName1 property
console.log(obj.getName2());
// "MyClass" because this is called in the context of obj
// using an arrow function getName2 and assigning it
// to obj's getName2 property, but which will preserve c's context
// nonetheless
console.log(obj.getName3());
// "obj" but why? Isn't the context of this enforced as that of MyClass? Shouldn't I get
// « The 'this' context of type 'obj' is not assignable to method's 'this' of type 'MyClass' »
console.log(g());
// Error, the 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.
// but isn't g declared in the global this context?
I have some questions regarding the functionality. They are outlined in the comments, but here they are summarized:
- Why does
console.log(obj.getName3());
show"obj"
? Shouldn't the context ofthis
be restricted to that ofMyClass
, resulting in an error message like:
The 'this' context of type 'obj' is not assignable to method's 'this' of type 'MyClass'
- I know that
g
is not declared within an object or class context. However, since it is defined at the global level, shouldn'tthis
refer toglobalThis
? If so, then why am I seeing the following error:
The 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.