lodash內(nèi)部方法getFuncName及setToString剖析詳解
getFuncName
getFuncName方法主要是獲取參數(shù)func的name屬性。
實現(xiàn)上主要通過函數(shù)的name屬性去獲取,同時也兼容原型鏈上屬性判斷。
源碼如下:
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方法源碼實現(xiàn)是賦值一個空對象,方便后續(xù)引用和保存。
源碼如下:
var realNames = {};
setToString
setToString方法主要是將參數(shù)“func”的“toString”方法設置為返回“string”。
該方法返回一個函數(shù)。
參數(shù)說明:
- 參數(shù)1:func要修改的函數(shù)。
- 參數(shù)2:字符串“toString”結(jié)果。
setToString方法在實現(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對外導出的方法,該方法可以創(chuàng)建一個返回參數(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方法通過getNative獲取原生的Object.defineProperty方法。
源碼如下:
import getNative from './_getNative.js';
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
identity
identity方法在之前的方法的篇章中介紹過,主要是返回參數(shù)本身,方便在迭代中的函數(shù)調(diào)用,是一種傳參形式。
源碼如下:
function identity(value) {
return value;
}
shortOut
在《 lodash里內(nèi)部方法getData和setData的實現(xiàn) 》中我們了解到shortOut方法的實現(xiàn)。
小結(jié)
本篇章我們簡單了解了lodash里的兩個內(nèi)部方法getFuncName和setToString的實現(xiàn),同時我們也在了解實現(xiàn)的過程中認識到了constant、defineProperty等內(nèi)部方法的實現(xiàn),更多關于lodash內(nèi)部方法的資料請關注腳本之家其它相關文章!
相關文章
http proxy 對網(wǎng)絡請求進行代理使用詳解
這篇文章主要為大家介紹了http proxy 對網(wǎng)絡請求進行代理使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
JavaScript?Canvas實現(xiàn)噪點濾鏡回憶童年電視雪花屏
這篇文章主要為大家介紹了JavaScript?Canvas實現(xiàn)噪點濾鏡回憶童年電視雪花屏,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
yocto queue微型隊列數(shù)據(jù)結(jié)構(gòu)源碼解讀
這篇文章主要為大家介紹了yocto queue微型隊列數(shù)據(jù)結(jié)構(gòu)源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
這篇文章主要介紹了Javascript基礎知識中關于內(nèi)置對象的相關知識的相關資料,需要的朋友可以參考下面小編薇大家?guī)淼木饰恼?/div> 2021-09-09
js 實現(xiàn)Material UI點擊漣漪效果示例
這篇文章主要為大家介紹了js 實現(xiàn)Material UI點擊漣漪效果示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09最新評論

