2

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

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

虽然它对其他对象(包括内置对象)按预期工作,例如

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

为什么会这样?

4

1 回答 1

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
}
于 2012-08-11T08:51:56.573 回答