Aganstrong 2021-04-08 11:41 采纳率: 56.6%
浏览 40
已采纳

js 这段代码什么意思?

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的这一块是什么意思吗?为什么写这段代码?

  • 写回答

2条回答 默认 最新

  • 爱在彩虹 2021-04-08 16:00
    关注

    整体代码的意思其实是对于 String 对象的 includes 函数的 polifill;整体思路其实是判断如果 String 对象上如果没有 includes 函数的话,则在 String 对象上手动添加一个 includes 函数以兼容不支持 String.prototype.includes 的浏览器。

    使用 Object.defineProperty方法是往对象添加新的属性,与直接通过 `对象.XX` 的方式添加有一个好处是,通过 defineProperty 添加的属性,默认情况下是不会被枚举的,比如通过 `for...in` 循环何 `Object.keys()` 就不能拿到其定义的属性。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效