how to explain this sequence of execution?

Y

Yan Huang

I have got bizarre results from the following sequence of simple code
snippet:

o={x:1,f:function (){return this.x}}
//Object
o.f()
//1
o.f.apply(o)
//1
o.f.apply === o.f.apply.apply
//true
o.f.apply.apply(o)
//TypeError: Function.prototype.apply was called on [object Object],
which is a object and not a function

All results are as expected except the last one. Anybody can help
explain this?

Thanks,
Yan Huang
 
Y

Yan Huang

Yan said:
I have got bizarre results from the following sequence of simple code
snippet:
o={x:1,f:function (){return this.x}}

It would be better to declare `o` here.
//Object
o.f()
//1
o.f.apply(o)
//1
o.f.apply === o.f.apply.apply

Even though `o.f.apply` and `o.f.apply.apply` reference same function
object (`Function.prototype.apply`, through prototype chain) ...
//true
o.f.apply.apply(o)
//TypeError: Function.prototype.apply was called on [object Object],
which is a object and not a function

... `o.f.apply(o)` and `o.f.apply.apply(o)` are being called on
different objects — former `apply` invokes `o.f` in context of `o`;
latter `apply` invokes another `apply` in context of `o`.

Latter case doesn't make much sense, since you're trying to invoke
`apply` on an object that's not a function (or more precisely, object
that doesn't implement [[Call]]). In cases like that `apply` throws
TypeError (see 15.3.4.3)

To make the latter call functionally identical to former one, you would
need something along these lines:

o.f.apply.apply(o.f, [o]);

IOW, call `apply` in context of `o.f` function, passing it `o` context
to be used by (first) `apply` that's being invoked.

(I hope this sentence makes sense :))

[...]

Thanks! You seems totally right.

-- Yan Huang
 
T

Thomas 'PointedEars' Lahn

Yan said:
As evident from the syntax, o is an object with literal value {x:1,
f:function() {return this.x}}.

As evident from the code, it is not. `o' becomes the name of a property of
the Global Object that refers to the initialized object. The suggestion was
to declare `o' a variable here.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top