比较括号中的数字返回的函数和未定义的返回的函数,然后使用IIFE执行。结果是NaN。发生了什么事?
function Point(x, y) {
this.x = x;
this.y = y;
}
console.log(
(
new Point(5, 8).sum || (() => undefined)
)() // IIFE : undefined
);
// sum() added
Point.prototype.sum = function () {
return this.x + this.y;
}
console.log(
(new Point(5, 8).sum)()
// 13
);
console.log(
// typeof : number
(
new Point(5, 8).sum || (() => undefined)
)()//! IIFE : NaN. ???? WH~~~Y????
);
在最后一个console.log,光秃秃的头脑崩溃了。让我知道为什么。...:(
在这种情况下被调用时,this
不是您所期望的;它来自周围的上下文,因为sum
函数未绑定。
这意味着您的功能主体最终会评估undefined + undefined
,即NaN
。
此问题的简化示例可以用:
let p = new Point(5, 8)
let f1 = p.sum
f1() //-> NaN
相反,您可以手动将参数传递为this
:
f1.call(p) //-> 13
或者您可以将该函数显式绑定到特定的this
:
let f2 = Point.prototype.sum.bind(new Point(5, 8))
f2() //-> 13