gpt4 book ai didi

javascript - 为什么 Object 原型(prototype)方法会覆盖 JavaScript 中的 String 和 Number 原型(prototype)方法?

转载 作者:行者123 更新时间:2023-11-30 15:43:08 27 4
gpt4 key购买 nike

尝试在 Object.prototype 以及 String.prototypeNumber.prototype 上定义一个 hashCode 方法>。我正在使用以下方法定义原型(prototype)方法:

Object.defineProperty(Object.prototype, 'hashCode', {
value:function() {/*code*/},
enumerable:false
});

String.prototype.hashCode = function() {/*code*/};
Number.prototype.hashCode = function() {/*code*/};

当我使用 ('', new String(), 3, new Number 创建数字或字符串时()),并在实例上调用 hashCodeObject.prototype.hashCode 方法始终运行,而不是 String.prototype.hashCodeNumber.prototype.hashCode

怎么了?

最佳答案

使属性描述符可写:true,否则在将属性写入继承它的对象时,它将被继承为不可写。 http://jsfiddle.net/5ox1a0f2 – 斜视

Object.defineProperty(Object.prototype, 'hashCode', {
value:function() {console.log('object')},
enumerable:false,
writable:true
});

String.prototype.hashCode = function() {console.log('string')};
Number.prototype.hashCode = function() {console.log('number')};

4..hashCode()

关于javascript - 为什么 Object 原型(prototype)方法会覆盖 JavaScript 中的 String 和 Number 原型(prototype)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40472571/

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