Object.defineproperty Or .prototype?
I've seen two different techniques of implementing non-native features in javascript, First is: if (!String.prototype.startsWith) { Object.defineProperty(String.prototype, 'sta
Solution 1:
In two cases you are adding a new property 'startsWith' in String.prototype.
First differs from the second in this cases:
You can configure the property to be enumerable, writable and configurable.
Writable - true means that you can change its value by assigning any value. If false - you can't change the value
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false,
writable: false, // Set to Falsevalue: function(searchString, position) {
position = position || 0;
returnthis.lastIndexOf(searchString, position) === position;
}
});
var test = newString('Test');
test.startsWith = 'New Value';
console.log(test.startsWith); // It still have the previous value in non strict modeEnumerable - true means that it will be seen in the for in loop.
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: true, // Set to Trueconfigurable: false,
writable: false,
value: function(searchString, position) {
position = position || 0;
returnthis.lastIndexOf(searchString, position) === position;
}
});
var test = newString('Test');
for(var key in test){
console.log(key) ;
}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.
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false, // Set to Falsewritable: false,
value: function(searchString, position) {
position = position || 0;
returnthis.lastIndexOf(searchString, position) === position;
}
});
deleteString.prototype.startsWith; // It will not delete the propertyconsole.log(String.prototype.startsWith);And one advice to you, don't change the prototypes of build in types.
Post a Comment for "Object.defineproperty Or .prototype?"