displayName
displayName

Reputation: 1106

Why does Function.toString work this way?

This object is just for testing:

const item = {
    id: 520,
    name: 'Item 520',
    props: [
        {id: 1, name: 'Prop 1'},
        {id: 2, name: 'Prop 2'}
    ]
}

This function takes as an argument property id, and returns function which gets property with that id from item passed to it.

const getItemPropById = propId => (item => item.props.find(p => p.id === propId))

So getItemPropById(1)(item) evaluates to {id: 1, name: "Prop 1"} as expected.

getItemPropById.toString() returns

"propId => (item => item.props.find(p => p.id === propId))". Nothing strange here.

Now, say I want a function which returns property with id 1.

const getItemPropWithId1 = getItemPropById(1)

This function will work as expected, BUT:

getItemPropWithId1.toString() returns

"item => item.props.find(p => p.id === propId)"

It does not return

"item => item.props.find(p => p.id === 1)"

So if this is the code that gets executed, how does getItemPropWithId1 "knows" to replace propId with 1, when it is called?

Are variables it uses stored somewhere inside it? And if so, can I access them without calling function, just like I can access its code?

Upvotes: 2

Views: 91

Answers (2)

Quentin
Quentin

Reputation: 944556

"Are variables it uses stored somewhere inside it?"

The variable is "stored" (this is an abstraction, it's really stored in a memory location and the implementation details are specific to the implmentation) in the propId variable you defined in the function argument.

And if so, can I access them without calling function, just like I can access its code?

No.

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308279

Generally speaking the result of calling toString() on any given object simply returns you a useful string representation that's mostly for debugging. It should help you understand what it does.

What toString() is explicitly not defined to do is give you a complete picture of the state of the object.

For example it is true that getItempropWithId1 will executed the code it shows on its toString() (i.e. that code is part of its state/content), but that's not all there is. In addition to that code, there's also a closure containing the value for propId (1, in this case). For some reason the authors of toString() have chosen not to include that closure in the toString() output (presumably because the closure can be quite massive and potentially contain thousands of arbitrarily large objects that would make the average toString() result useless).

There is no general-purpose way to access the values in a closure directly. Some debuggers will display it, but your code pretty much can't access them.

tl;dr The code toString() shows is just part of what defines the object.

Upvotes: 4

Related Questions