为什么我不能将未定义分配给 window.load

Why can't I assign undefined to window.load?

本文关键字:window load 分配 未定义 不能 为什么      更新时间:2023-09-26

我刚刚注意到这种奇怪的效果

window.onload = undefined;
console.log(window.onload); // print 'null', instead of 'undefined'

虽然它按预期适用于其他对象,包括内置对象,例如

Array.prototype.slice = undefined;
console.log(Array.prototype.slice); // print 'undefined'

为什么会这样呢?

这种行为是这样的,因为.onload是一个二传手,它的工作原理是这样的:

window = {
    // Other window properties and methods
    get onload() {
        // returns null if no function was added or returns the last function added
    },
    set onload(value) {
        if (typeof value === 'function') {
            loadListener = value; // loadListener is the function called when load event is triggered
        }
    }
    // Other window properties and methods
}