我见过两种在 javascript 中实现非 native 功能的不同技术, 首先是:
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;
}
我知道第二种技术用于将任何方法附加到特定标准内置对象的原型(prototype)链,但第一种技术对我来说是新的。 任何人都可以解释它们之间的区别是什么,为什么使用一个,为什么不使用一个,以及它们的意义是什么。
最佳答案
在两种情况下,您要在 String.prototype
中添加新属性“startsWith”。
在这种情况下,第一个不同于第二个:
您可以将属性配置为可枚举
、可写
和可配置
。
Writable - true
表示您可以通过分配任何值来更改其值。如果为 false - 您不能更改该值
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false,
writable: false, // Set to False
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
var test = new String('Test');
test.startsWith = 'New Value';
console.log(test.startsWith); // It still have the previous value in non strict mode
Enumerable - true
表示它将在 for in
循环中看到。
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: true, // Set to True
configurable: false,
writable: false,
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
var test = new String('Test');
for(var key in test){
console.log(key) ;
}
Configurable - true
当且仅当可以更改此属性描述符的类型并且可以从相应对象中删除该属性时。
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false, // Set to False
writable: false,
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
delete String.prototype.startsWith; // It will not delete the property
console.log(String.prototype.startsWith);
还有一个建议,不要更改内置类型的原型(prototype)。
关于javascript - Object.defineProperty 还是 .prototype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961414/