# invoke
# Description
调用 object 对象 path 上的方法。
# Params
(object, path, args)
# Return
{*}
# Depend
import castPath from './.internal/castPath.js'
import last from './last.js'
import parent from './.internal/parent.js'
import toKey from './.internal/toKey.js'
# Code
function invoke(object, path, args) {
path = castPath(path, object)
object = parent(object, path)
const func = object == null ? object : object[toKey(last(path))]
return func == null ? undefined : func.apply(object, args)
}
# Analyze
首先通过
castPath拿到path路径数组根据
parent方法,拿到path路径数组倒数第二个值的对象,找不到的话就是object本身,然后赋值给object如果 拿到的
parent为null,则将object赋值给func,否则 将path路径中最后一个取出,也就是方法名,通过toKey转为合法的key,拿到值,赋值给func判断 如果
func为null或者undefined,则返回undefined, 否则使用apply调用func, 这里传入的this为object,也就是parent的值。这样做是为了不改变this指向,和用原始对象 直接.的效果一致args传入的应当为 数组
# Remark
- Function.prototype.apply() MDN (opens new window) 方法调用一个具有给定 this 值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
# Example
const obj = {
a: {
b: {
c: [1, 2, 3, 4, ['test','invoke']]
}
}
}
console.log(invoke(obj, 'a.b.c.4.join')) // test,invoke