0

I am designing an API and I want to find a way, to figure out if a function expression is a arrow function.

var o1 = {bar:function(){
    return this.value;
}};
var o2 = {bar:() => {
    return this.value;
}}


function foo(o){
    let baz = {value:10};
    return o.bar.call(baz)
}

console.log(foo(o1)) //10

console.log(foo(o2)) // undefined

Now before I get downvoted because of the obvious answer that es6 arrow functions have a lexically bound this. Thats not what I am asking here. I want a way to programmatically find out if an arrow function is being used, so I can throw. Is it possible?

It seems like a easy way to go about this would be to check the name property

function foo(f){
    if(!f.name){
        throw Error("f is an arrow function")
    }
    let baz = {value:10};
    return f.call(baz)
}



console.log(  foo(() => this.value) ) // f is a arrow function

But then it looses its object form. As soon as an es6 function expression becomes a property on an object, it has a name value, so I cant test then. What else can one test for?

  • TL;DR from the linked duplicate, there is no guaranteed way to be able to tell. – Jared Smith Aug 16 '20 at 23:21
  • 3
    "*I am designing an API*" - then you should *not* try to detect whether someone passed an arrow function or not. It's their business if they want to use your `this` argument or not. You might offer a warning in development mode, and you should throw an exception when they fail to pass a function, but you should not care what the function does and how. – Bergi Aug 16 '20 at 23:34
  • @Bergi Thanks for the tip. In my case, I think what you said will actually bring more flexibility, but on that note, I don't think its particularly wrong to "lock down" certain ways to do certain things. – dannyvidal Aug 17 '20 at 00:31

0 Answers0