编写 polyfill — Javascript

编写 polyfill — javascript

一段代码,提供某些浏览器或环境本身不支持的功能。简单来说,就是浏览器后备。

在为call()apply()bind()方法编写polyfill之前,请检查call、apply和bind的功能。

let details = {
  name: 'manoj',
  location: 'chennai'
}

let getdetails = function (...args) {
  return `${this.name} from ${this.location}${args.join(', ') ? `, ${args.join(', ')}` : ''}`;
}

1。调用方式:

让我们为call()创建一个polyfill。我们将向 function.prototype 添加自定义 call 方法,以使其可供所有函数访问。

getdetails.call(details, 'tamil nadu', 'india');  // manoj from chennai, tamil nadu, india

// polyfill
function.prototype.mycall = function (ref, ...args) {
  if (typeof function.prototype.call === 'function') {  // checks whether the browser supports call method
    return this.call(ref, ...args);
  } else {
    ref = ref || globalthis;
    let funcname = math.random();  // random is used to overwriting a function name
    while (ref.funcname) {
      funcname = math.random();
    }
    ref[funcname] = this;
    let result = ref[funcname](...args);
    delete ref[funcname];
    return result;
  }
}

getdetails.mycall(details, 'tamil nadu', 'india');  // manoj from chennai, tamil nadu, india

2。申请方法:

让我们为apply() 创建一个polyfill。我们将向 function.prototype 添加自定义 apply 方法,以使其可供所有函数访问。

getdetails.apply(details, ['tamil nadu', 'india']);  // manoj from chennai, tamil nadu, india

// polyfill
function.prototype.myapply = function (ref, args) {
  if (typeof function.prototype.apply === 'function') {  // checks whether the browser supports call method
    this.apply(ref, args);
  } else {
    ref = ref || globalthis;
    let funcname = math.random();  // random is to avoid duplication
    while (ref.funcname) {
      funcname = math.random();
    }
    ref[funcname] = this;
    let result = ref[funcname](args);
    delete ref[funcname];
    return result;
  }
}

getdetails.myapply(details, 'tamil nadu', 'india');  // manoj from chennai, tamil nadu, india

3。绑定方法

让我们为bind() 创建一个polyfill。我们将向 function.prototype 添加自定义 bind 方法,以使其可供所有函数访问。

let getFullDetails = getDetails.bind(details, 'Tamil Nadu');
getFullDetails();  // Manoj from Chennai, Tamil Nadu
getFullDetails('India');  // Manoj from Chennai, Tamil Nadu, India

// Polyfill
Function.prototype.myBind = function (ref, ...args) {
  if (typeof Function.prototype.bind === 'function') {
    return this.bind(ref, ...args);
  } else {
    let fn = this;
    return function (...args2) {
        return fn.apply(ref, [...args, ...args2]);  // Merge and apply arguments
    }
  }
}

let getFullDetails = getDetails.myBind(details, 'Tamil Nadu');  // Manoj from Chennai, Tamil Nadu
getFullDetails('India');  // Manoj from Chennai, Tamil Nadu, India

感谢您的阅读!我希望您发现这个博客信息丰富且引人入胜。如果您发现任何不准确之处或有任何反馈,请随时告诉我。

以上就是编写 polyfill — Javascript的详细内容,更多请关注其它相关文章!