[学习JS和this
关键字的行为...想了解下面发生的事情
声明一个类(point2)
class point2 {
constructor(x,y) {
this.x = x;
this.y=y;
}
dump() {
(print = () => {
console.log(this.x + " " + this.y);
}).call(this);
}
}
p1 = new point2(1,2);
p1.dump(); // prints undefined
但不知道为什么p1.dump()
调用未打印
[以为p1.dump()
会将其设置为point2对象,然后print arrow
函数将继承this
(这将是point2对象),因此希望它可以打印1 2
[p1.dump()
返回undefined
,因为您什么都不返回。
class point2 {
constructor(x,y) {
this.x = x;
this.y=y;
}
dump() {
(print = () => {
console.log(this.x + " " + this.y);
}).call(this);
return true; // return something here and the console.log will have result
}
}
p1 = new point2(1,2);
p1.dump(); // undefined
undefined
是方法返回的内容。因此,由于该方法没有return
关键字,因此它将返回undefined
。 1 2
已按预期方式注销。