2016-11-29 38 views
1

像这样:有没有办法访问函数的预绑定值?

const a = (arg0, arg1, arg2) => { 
    console.log(arg0); 
}; 
const b = a.bind(null, 1, 2, 3) 

现在假设我只有b,是有可能得到的绑定前值列表?我的意思是值1,2,3

如果可能的话,怎么样?

+0

如果你有一些变量的所有这些参数,可以比对,否则你不能。相同的在'var b = 5 + 2'和* get * 2 ... – Justinas

+0

@Justinas不完全,我有b,所以如果我做b.call(),那么参数是肯定的,所以我想知道:既然这是肯定的,我能以某种方式知道它吗? –

+0

所以你想获得传递给它的所有参数吗? – Justinas

回答

1

如果你编写自己的绑定功能,您可以将新的属性给它,一个函数可以有属性添加到它像任何其他对象。

function bind(fn, thisArg, ...boundArgs) { 
 
    const func = function(...args) { 
 
    return fn.call(thisArg, ...boundArgs, ...args) 
 
    } 
 
    // you can hide the properties from public view using 
 
    // defineProperties, unfortunately they are still public 
 
    Object.defineProperties(func, { 
 
    __boundArgs: { value: boundArgs }, 
 
    __thisArg: { value: thisArg }, 
 
    __boundFunction: { value: fn } 
 
    }) 
 
    return func 
 
} 
 

 
const a = (a, b, c) => console.log(a, b, c) 
 

 
const b = bind(a, null, 1, 2, 3) 
 

 
b() 
 

 
console.log(b.__boundArgs) 
 
console.log(b.__thisArgs) 
 
console.log(b.__boundFunction)
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

的第一个参数Function.prototype.bindthis ARG。

要回答这个问题,如果你使用的是Chrome,你可以在绑定的功能,访问信息的属性[[BoundArgs]]。运行代码,并检查您的控制台

const a = (arg0, arg1, arg2) => { 
 
    console.log(arg0, arg1, arg2); 
 
}; 
 
const b = a.bind(null, 1, 2, 3) 
 
b() 
 
console.dir(b)

+0

我可以看到BoundArgs在那里,但我怎么能得到它? –

+0

我在Node.js env中,我可以在控制台中看到BoundArgs与console.dir()在一起,但我怎么能得到它? t.bound() VM501:1遗漏的类型错误:t.bound不是一个函数(...) –

+0

不要以为你可以..你总是可以编写自己的绑定功能..它只有几行 – synthet1c

相关问题