亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

lodash內(nèi)部方法getFuncName及setToString剖析詳解

 更新時(shí)間:2022年09月01日 08:46:31   作者:EricHong  
本篇章我們主要是通過(guò)了解lodash里的兩個(gè)內(nèi)部方法getFuncName方法和setToString方法,在實(shí)際開(kāi)發(fā)中我們也可以借鑒方法的實(shí)現(xiàn)思路,在需要的時(shí)候簡(jiǎn)單封裝一下,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

getFuncName

getFuncName方法主要是獲取參數(shù)func的name屬性。

實(shí)現(xiàn)上主要通過(guò)函數(shù)的name屬性去獲取,同時(shí)也兼容原型鏈上屬性判斷。

源碼如下:

import realNames from './_realNames.js';
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function getFuncName(func) {
  var result = (func.name + ''),
      array = realNames[result],
      length = hasOwnProperty.call(realNames, result) ? array.length : 0;
  while (length--) {
    var data = array[length],
        otherFunc = data.func;
    if (otherFunc == null || otherFunc == func) {
      return data.name;
    }
  }
  return result;
}

realNames

realNames方法源碼實(shí)現(xiàn)是賦值一個(gè)空對(duì)象,方便后續(xù)引用和保存。

源碼如下:

var realNames = {};

setToString

setToString方法主要是將參數(shù)“func”的“toString”方法設(shè)置為返回“string”。

該方法返回一個(gè)函數(shù)。

參數(shù)說(shuō)明:

  • 參數(shù)1:func要修改的函數(shù)。
  • 參數(shù)2:字符串“toString”結(jié)果。

setToString方法在實(shí)現(xiàn)上借助了baseSetToString內(nèi)部方法和shortOut內(nèi)部方法。

源碼如下:

import baseSetToString from './_baseSetToString.js';
import shortOut from './_shortOut.js';
var setToString = shortOut(baseSetToString);

baseSetToString

import constant from './constant.js';
import defineProperty from './_defineProperty.js';
import identity from './identity.js';
var baseSetToString = !defineProperty ? identity : function(func, string) {
  return defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(string),
    'writable': true
  });
};

constant

constant方法是lodash對(duì)外導(dǎo)出的方法,該方法可以創(chuàng)建一個(gè)返回參數(shù)value的函數(shù),返回的是新的常量函數(shù)。

使用如下:

var objects = _.times(2, _.constant({ 'a': 1 }));
console.log(objects);
// => [{ 'a': 1 }, { 'a': 1 }]
console.log(objects[0] === objects[1]);
// => true

源碼如下:

function constant(value) {
  return function() {
    return value;
  };
}

defineProperty

defineProperty方法通過(guò)getNative獲取原生的Object.defineProperty方法。

源碼如下:

import getNative from './_getNative.js';
var defineProperty = (function() {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

identity

identity方法在之前的方法的篇章中介紹過(guò),主要是返回參數(shù)本身,方便在迭代中的函數(shù)調(diào)用,是一種傳參形式。

源碼如下:

function identity(value) {
  return value;
}

shortOut

在《 lodash里內(nèi)部方法getData和setData的實(shí)現(xiàn) 》中我們了解到shortOut方法的實(shí)現(xiàn)。

小結(jié)

本篇章我們簡(jiǎn)單了解了lodash里的兩個(gè)內(nèi)部方法getFuncName和setToString的實(shí)現(xiàn),同時(shí)我們也在了解實(shí)現(xiàn)的過(guò)程中認(rèn)識(shí)到了constant、defineProperty等內(nèi)部方法的實(shí)現(xiàn),更多關(guān)于lodash內(nèi)部方法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論