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”方法設(shè)置為返回“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對外導(dǎo)出的方法,該方法可以創(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)的過程中認(rèn)識到了constant、defineProperty等內(nèi)部方法的實現(xiàn),更多關(guān)于lodash內(nèi)部方法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微信小程序(應(yīng)用號)簡單實例應(yīng)用及實例詳解
這篇文章主要介紹了微信小程序(應(yīng)用號)簡單實例應(yīng)用的相關(guān)資料,需要的朋友可以參考下2016-09-09
autojs長寬不定的圖片在正方形圖片居中實現(xiàn)詳解
這篇文章主要為大家介紹了autojs長寬不定的圖片在正方形圖片居中實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
js面向?qū)ο缶幊蘋OP及函數(shù)式編程FP區(qū)別
這篇文章主要為大家介紹了js面向?qū)ο缶幊蘋OP及函數(shù)式編程FP的區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

