gpt4 book ai didi

javascript - 替换内置函数的原型(prototype)是否非法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:42:27 24 4
gpt4 key购买 nike

Date.prototype = { foo : 1 };
Date.prototype.foo // => null

奇怪的是,替换内置函数的原型(prototype)会被简单地忽略而不会发出任何错误,但我找不到任何提及它的文章、书籍或博客文章。

最佳答案

不,这不是非法的(因为规范不会阻止您这样做)。它通常在您自己定义的函数上完成。

它在 JavaScript 规范定义的函数上被忽略,因为它们的 prototype 属性是只读。来自 the specification for Date.prototype :

The initial value of Date.prototype is the intrinsic object %DatePrototype% (20.3.4).

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

(我的重点。)

分配给它只是静默在松散模式下被忽略;在严格模式下(我们基本上一直都应该使用),这是一个错误:

"use strict";
Date.prototype = {};


超出问题范围,您可以通过 Object.defineProperty 定义行为相同的自己的只读属性:

var obj = {};
Object.defineProperty(obj, "answer", {
value: 42,
writable: false // This is for emphasis, it's actually the default
});
tryLoose();
tryStrict();
function tryLoose() {
console.log("Trying to assign new value in loose mode.");
obj.answer = "It's complicated.";
console.log("After assignment, obj.answer = " + obj.answer);
}
function tryStrict() {
"use strict";
console.log("Trying to assign new value in strict mode.");
obj.answer = "It's complicated.";
console.log("We won't get here.");
}

关于javascript - 替换内置函数的原型(prototype)是否非法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37420091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com