Javascript 对象箭头函数和 this
Javascript Objects Arrow-function and this
正在学习 JS 和 this
关键字的行为...想了解下面发生的事情
声明了一个 Class ( 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()
returns undefined
因为你 return 什么都没有。
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
是什么方法returns。所以因为该方法没有 return
关键字所以它将 return undefined
。 1 2
按预期注销。
正在学习 JS 和 this
关键字的行为...想了解下面发生的事情
声明了一个 Class ( 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()
returns undefined
因为你 return 什么都没有。
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
是什么方法returns。所以因为该方法没有 return
关键字所以它将 return undefined
。 1 2
按预期注销。