【发布时间】:2023-03-24 16:56:01
【问题描述】:
我见过两种在 javascript 中实现非原生功能的不同技术, 首先是:
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
}
第二个是:
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
我知道第二种方法用于将任何方法附加到特定标准内置对象的原型链上,但第一种方法对我来说是新的。 谁能解释它们之间有什么区别,为什么使用一个,为什么不使用一个,它们的意义是什么。
【问题讨论】:
-
enumerable、configurable和writable都默认为false,因此没有必要。无论如何,这样做的好处是,呃,这样定义的属性不是可枚举的、可配置的或可写的,所有这些都是您可能想要的。 -
是的,但是发现
developer.mozilla.org上的官方文档有点混乱。如果我们可以将属性添加到特定标准内置对象的原型中,那么defineProperty实际上做了什么,那是令人困惑的部分。
标签: javascript string object prototype defineproperty