class Person {
name: string;
constructor(initName: string){
this.name = initName
}
// これがクラスメソッド
greeting(){
console.log("hello")
}
}
class Person {
name: string;
constructor(initName: string){
this.name = initName
}
greeting(){
// ここのthisはPerson
console.log(this.name)
}
}
const quill = new Person("Quill");
const anotherQuill: {
anotherGreeting: () => void;
}
// この場合のthisはanotherQuill
// anotherQuillにはnameがないのでundefinedになる
anotherQuill.anotherGreeting();
class Person {
name: string;
constructor(initName: string){
this.name = initName
}
greeting(this: {name: string}){
console.log(this.name)
}
}
const quill = new Person("Quill");
const anotherQuill: {
anotherGreeting: () => void;
}
// ここでエラーになる
anotherQuill.anotherGreeting();
class Person {
name: string;
constructor(initName: string){
this.name = initName
}
// thisにPersonを設定する
greeting(this: Person){
console.log(this.name)
}
}
const quill = new Person("Quill");
const anotherQuill: {
greeting: quill.greeting
}
anotherQuill.greeting();
class Person {
name: string;
constructor(public name: string){
}
// thisにPersonを設定する
greeting(this: Person){
console.log(this.name)
}
}
const quill = new Person("Quill");
const anotherQuill: {
greeting: quill.greeting
}
anotherQuill.greeting();