为什么我不能将undefined分配给window.load?

时间:2012-08-11 08:09:03

标签: javascript undefined

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

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

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

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

为什么会这样?

1 个答案:

答案 0 :(得分:4)

这种行为是这样的,因为.onload是一个setter,它的工作原理如下:

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
}