if (!String.prototype.includes) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch (error) {}
return result;
}());
var includes = function(search) {
...
}
if (defineProperty) { //已有属性修改
defineProperty(String.prototype, 'includes', {
'value': includes,
'configurable': true,
'writable': true
});
} else {
String.prototype.includes = includes;
}
}());
}
我发现了这样一段代码,谁能说一下这段代码里关于defineProperty的这一块是什么意思吗?为什么写这段代码?
整体代码的意思其实是对于 String 对象的 includes 函数的 polifill;整体思路其实是判断如果 String 对象上如果没有 includes 函数的话,则在 String 对象上手动添加一个 includes 函数以兼容不支持 String.prototype.includes 的浏览器。
使用 Object.defineProperty方法是往对象添加新的属性,与直接通过 `对象.XX` 的方式添加有一个好处是,通过 defineProperty 添加的属性,默认情况下是不会被枚举的,比如通过 `for...in` 循环何 `Object.keys()` 就不能拿到其定义的属性。
这是Object.defineProperty定义对象新属性,你那一端是判断是否支持Object.defineProperty,并返回对象