2016-06-29 10 views
0

私は関数を作成し、以下のように引数をバインドしました。Javascript、バインドされた関数の名前を取得

function myFunc(){} 

let boundFunc = myFunc.bind(argument); 

しかし、その後、私は名前を取得する必要が別の関数への引数として、このバウンド関数を渡します。次

function doTheThing(callable){ 
    console.log(callable.name + " did the thing"); 
} 

doTheThing(boundFunc); 

プリントbound did the thingではなくmyFunc did the thingアウト。バインドされた関数の名前を取得する方法はありますか?


callable.callerUncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.での結果とは、ブラウザの標準ではありません。あなたは短いcallable.nameが行うcallable.name.substring(6)

+0

私が知る限り、 '.bind()'はまったく新しい関数を返します。古い関数のインスタンスをどこかに保持しない限り、その名前を判別することはできません。 –

答えて

0

長い話を元の名前を得ることができるので、それは、bound myFunc did the thingを印刷し

function myFunc(){} 
 

 
let boundFunc = myFunc.bind(null); 
 

 
function doTheThing(callable){ 
 
    console.log(callable.name + " did the thing"); 
 
} 
 

 
doTheThing(boundFunc);

1

グーグルクロームV 51.0.2704.103は異なる結果を与えます作業し、bound myFuncを生産します。


transpiled typescriptを使用していたため、私のバージョンが機能しませんでした。このスニペット:

class MyClass{ 
    static doTheThing(callable) {} 
} 

let myFunc = MyClass.doTheThing.bind(null); 

function handleCall(callable){ 
    console.log(callable.name) 
} 

handleCall(myFunc); 

は生成します。

var MyClass = (function() { 
    function MyClass() { 
    } 
    MyClass.doTheThing = function (callable) {}; 
    return MyClass; 
}()); 
var myFunc = MyClass.doTheThing.bind(null); 
function handleCall(callable) { 
    console.log(callable.name); 
} 
handleCall(myFunc); 

キーこれは、匿名関数は、それゆえの名前のためにundefinedを返しますMyClass.doTheThing作るラインMyClass.doTheThing = function (callable) {};です。これにより、callable.nameは"bound " + undefinedまたは"bound "を返します。

要するに、バインドされた関数の名前を取得できますが、ガール関数には名前がありません。

+0

FF 49.0a2でも動作します。何らかの理由で名前がパターン "bound"に一致しなかった場合、静かに失敗しないので、元の名前に対して '/^bound(。*)$ /。exec(callable.name)[1]'を提案することもできます。 .. "? – Siguza

+0

私はスニペットも私のために働いていることを知っていますが、同じことをしている元のコードはそうではありません。 – timlyo

+0

@timlyo実際のコードを投稿できますか? 'callable()'が本当の価値を返すかどうかをチェックしているので、質問にあるものはうまく動作しません。また、バインドしているものを確認してください。 'bind'の最初の引数は、あなたが' this'を参照したいものであれば、コンテキストです。 – Schlaus

関連する問題