面试题答案
一键面试class MyClass {
method1(): this {
console.log('method1 executed');
return this;
}
method2(): this {
console.log('method2 executed');
return this;
}
}
使用this
作为返回类型,是为了确保链式调用的连贯性。在链式调用中,每次调用方法后返回的对象应该能够继续调用其他方法,通过返回this
,当前对象的实例就可以持续作为后续方法调用的主体,从而实现像obj.method1().method2()
这样的链式操作。如果不返回this
,链式调用就无法继续进行,因为返回其他类型将导致后续方法无法在返回值上调用。