将这两个功能与支架进行了比较。 IIFE执行。结果 NaN
The two functions were compared to the bracket. IIFE execution. Results NaN
括号中数值return的函数和未定义return的函数是用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
括号中数值return的函数和未定义return的函数是用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