为什么对象原型方法会覆盖JavaScript中的字符串和数字原型方法?
正在尝试在为什么对象原型方法会覆盖JavaScript中的字符串和数字原型方法?,javascript,inheritance,prototype-chain,Javascript,Inheritance,Prototype Chain,正在尝试在对象.prototype以及字符串.prototype和数字.prototype上定义hashCode方法。我使用以下方法定义原型方法: Object.defineProperty(Object.prototype, 'hashCode', { value:function() {/*code*/}, enumerable:false }); String.prototype.hashCode = function() {/*code*/}; Number.prototype
对象.prototype
以及字符串.prototype
和数字.prototype
上定义hashCode
方法。我使用以下方法定义原型方法:
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()
)中的任何一种创建一个数字或字符串,并调用实例上的hashCode
,则对象.prototype.hashCode
方法总是运行,而不是字符串.prototype.hashCode>或数字.prototype.hashCode
有什么问题吗?将属性描述符设置为可写:true,否则在继承它的对象上写入该属性时,它将作为不可写继承。
-斜视
Object.defineProperty(Object.prototype,'hashCode'{
值:function(){console.log('object')},
可枚举:false,
可写:对
});
String.prototype.hashCode=function(){console.log('String')};
Number.prototype.hashCode=function(){console.log('Number')};
4..hashCode()
混合属性定义和属性分配可能会导致此类问题
如果您在String.prototype
和Number.prototype
中也使用属性定义,则此选项有效:
Object.defineProperty(Object.prototype,'hashCode'{
值:function(){console.log('object')},
可枚举:false
});
Object.defineProperty(String.prototype,'hashCode'{
值:function(){console.log('string')},
可枚举:false
});
Object.defineProperty(Number.prototype,'hashCode'{
值:函数(){console.log('number')},
可枚举:false
});
(4) .hashCode();//“数字”
(“”).hashCode();//“string”
FYI,如果我还使用Object.defineProperty(string.prototype…
)定义字符串和数字原型方法,那么它会按预期工作。事实上,它的工作方式与使用string.prototype.hashCode=function()不同…
让我感到困惑。将属性描述符设置为可写:true
,否则当在继承它的对象上写入该属性时,它将被继承为不可写。哦,太酷了。我没有意识到它在默认情况下是不可写的。谢谢!关于此可写
行为的密切相关讨论:的确。这也很有趣t如果我在调用Object.defineProperty之前设置了String.prototype.hashCode和Number.prototype.hashCode(Object.prorotype…
函数按预期工作,因此如果您创建它们,然后使它们在Object.prototype上不可写,它们已经被写入并且不会丢失它们的值。注意String.prototype.hashCode
和Number.prototype.hashCode
将是可枚举的。喜欢数字文本上的双点调用。我是尝试调用'3.hashCode()'但调用'3..hashCode()'时在测试中获取语法错误是一个很好的技巧。