我已经看到了两种在 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;
}
我知道第二种方法用于将任何方法附加到特定标准内置对象的原型链上,但第一种技术对我来说是新的。任何人都可以解释它们之间有什么区别,为什么使用一个,为什么不使用一个以及它们的意义是什么。