String.prototype = {};
String.prototype; //returns original value, i.e hasn't changed
function my_func(){};
my_func.prototype = {};
my_func.prototype; // returns {}, i.e has changed.
为什么 String.prototype 没有改变?
最佳答案
您不能更改它,因为 String
的 prototype
属性根据 spec 是不可写和不可配置的其中指出:
String.prototype
The initial value of String.prototype is the intrinsic object %StringPrototype%.This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false )
您自己的对象的原型(prototype)是可写的,您可以使用 Object.getOwnPropertyDescriptor()
查看:
// String
console.log("String",
Object.getOwnPropertyDescriptor(String, 'prototype'))
// Custom Object
function my_func(){};
console.log("Your own object",
Object.getOwnPropertyDescriptor(my_func, 'prototype'))
可写的意思是:
writable
true if and only if the value associated with the property may be changed (data descriptors only).
你也不能让它可写,因为它是不可配置的:
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
发件人:MDN
这并不意味着您不能更改原型(prototype)对象,您只是不能删除它或用其他东西替换它。例如你可以添加到它(不是我推荐这个):
String.prototype.init = function (){
return this.slice(0, 1).toUpperCase()
}
h = "hello"
console.log(h.init())
关于javascript - 为什么我们不能改变内置函数构造函数的原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53148550/