Object.method(o)
looks on the Object
object (Object
is a real object in JavaScript) for a property called method
and tries to call it passing in the variable o
. During the call, this
will be Object
.
o.method()
looks on the object referenced by the variable o
for a property called method
and tries to call it, not passing anything in. During the call, this
will be o
.
As you can see, they do quite different things.
I noticed that all the methods of a particular object can be called from the actual object instance...or by passing the object to Object.method()
as an argument.
No, they cannot. Your example Array.reverse(a)
fails on a standard implementation of Array
because Array
doesn't have a property called reverse
and so it can't be called as a function. Edit: You note in the comments that it works in Firefox's scratchpad, and I just verified that. That means Firefox's SpiderMonkey JavaScript engine is applying a non-standard extension to Array
which provides a static implementation of reverse
. That's specific to Firefox's Array
, not general to all objects. (If you make your own Foo
, for instance, its prototype functions don't magically get added to Foo
as well.)
The standard way to make the near-equivalent to a.reverse()
would be via the prototype, like this:
Array.prototype.reverse.call(a);
That does work in standard engines. So let's look at what it does:
It gets the prototype
property from Array
.
It gets the reverse
property from the object it got in #1.
It calls the function that property referenced using the Function#call
feature of JavaScript function objects to make this
be the argument you pass into call
during the course of the function call.
When you create an array, the object gets an underlying prototype. That prototype is the object referenced by Array.prototype
when the new array is created. So a
has a reverse
property because its underlying prototype has a reverse
property.
Doing a.reverse()
does this:
Gets the reverse
property from the a
object. Since (normally) a
won't have its own property called reverse
, standard JavaScript property lookup looks to a
's underlying prototype. It finds the property there and uses its value.
Calls that function such that this
is a
within the call.
As you can see, the end result is the same provided that the underlying prototype of a
and Array.prototype
still refer to the same object. (It's possible for them not to, although in the case of Array
or any other built-in, if someone replaced [as opposed to augmenting] Array.prototype
, that would be a Bad Thing(tm).)