In the section Creating CheckList Rows on Submit,
myTruck.createOrder.call(myTruck, data);
checkList.addRow.call(checkList, data);
I’m wondered can I myTruck.createOrder(data)
instead of using call
?
In the section Creating CheckList Rows on Submit,
myTruck.createOrder.call(myTruck, data);
checkList.addRow.call(checkList, data);
I’m wondered can I myTruck.createOrder(data)
instead of using call
?
Hi there!
If you change the code to myTruck.createOrder(data)
instead of myTruck.createOrder.call(myTruck, data)
, what error do you get?
If you put a breakpoint inside of createOrder
and click the Submit button, what is the value of this
?
What is the value of this
if you change the code back to myTruck.createOrder.call(myTruck, data)
and submit the form?
The reason it is necessary to use call
is because you have to explicitly set the value of this
to myTruck
.
Unlike languages such as Java, the this
property is dynamic. Sometimes, you need to set it explicitly using call
or bind
, otherwise its value may not be what you expect. This is often the case inside of callbacks, such as the one you are passing to formHandler.addSubmitHandler
.
Does that help clarify what is going on?
-Chris
I know that this will be different when using in different scope, but there seems no error I got, so I asked this question!
I set a breakpoint and tried both - they both result in the exact same value for ‘this’.
If you call createOrder on the myTruck object (without using call), ‘this’ would refer to the myTruck Object - What else could it possible be set too?
You and @jossciiare are right on target.
The value of this
is the same whether you use .call
or not.
(There’s no other value it could have in the context of this code sample.)
That was an oversight on our part in the first printing of the book. Using .call
was necessary in an early revision of the example code. But after the code changed, we forgot to remove .call
and its accompanying explanation.