简体   繁体   English

JavaScript原型

[英]JavaScript Prototypes

Why in MDN functions polyfills use "if (!Array.prototype.filter)" ? 为什么在MDN函数中polyfill使用“if(!Array.prototype.filter)”?

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    var t = Object(this);
    var len = t.length >>> 0;    
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

What do you need to use it? 你需要用什么?

That's how they check to see if the thing they're polyfilling is already present. 这就是他们如何检查他们是否已经存在填充的东西。

To use that specific example: Array.prototype refers to the object that is the prototype of all arrays. 要使用该特定示例: Array.prototype指的是作为所有数组原型的对象。 So Array.prototype.filter is the property that arrays inherit that provides the filter method. 所以Array.prototype.filter是数组继承的属性,它提供了filter方法。 By doing if (!Array.prototype.filter) , the code checks to see if that property already exists with a truthy value (a function reference is truthy) and doesn't try to add it if it's present. 通过执行if (!Array.prototype.filter) ,代码检查该属性是否已经存在且具有真值(函数引用是真实的)并且如果它存在则不尝试添加它。 Reading the value of Array.prototype.filter will yield undefined (a falsy value) if filter isn't present on Array.prototype , which tells the code it needs to add the polyfill. 如果Array.prototype上没有filter ,那么读取Array.prototype.filter的值将产生undefined (一个假值),它告诉添加polyfill所需的代码。

What do you need to use it? 你需要用什么?

if the native method does exist the polyfill doesn't overwrite it 如果本机方法确实存在,则polyfill不会覆盖它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM