javascript - 为什么我们不能改变内置函数构造函数的原型(prototype)?

标签 javascript

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 没有改变?

最佳答案

您不能更改它,因为 Stringprototype 属性根据 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/

相关文章:

javascript - 如果满足条件则匹配整个单词

javascript - 可观察的订阅无法以非常短的间隔处理连续传入的数据

javascript - 如何使用过滤数组删除数组中的项目?

javascript - 如何更改文本区域选定文本的颜色?

Javascript - 范围在回调中丢失

javascript - Firefox addon sdk同步请求

javascript - 使用 function.apply(...) 时保留函数的作用域

javascript - 如何让它像Chrome中那样显示?

javascript - 检测是否从同一网站打开了一个窗口

javascript - 错误: Cannot find module 'extract-text-webpack-plugin'