Possible Duplicate:
Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?
I noticed that all the methods of a particular object can be called from the actual object instance, i.e., object.method(); or by passing the object to Object.method() as an argument. For example:
var a = ['one', 2, 3, 'four'];
a.reverse();
// OR
Array.reverse(a);
I seemed to get the same behaviour. I was wondering what the difference was and when one would be used over the other?
Object.method(o)looks on theObjectobject (Objectis a real object in JavaScript) for a property calledmethodand tries to call it passing in the variableo. During the call,thiswill beObject.o.method()looks on the object referenced by the variableofor a property calledmethodand tries to call it, not passing anything in. During the call,thiswill beo.As you can see, they do quite different things.
No, they cannot. Your example
Array.reverse(a)fails on a standard implementation ofArraybecauseArraydoesn’t have a property calledreverseand 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 toArraywhich provides a static implementation ofreverse. That’s specific to Firefox’sArray, not general to all objects. (If you make your ownFoo, for instance, its prototype functions don’t magically get added toFooas well.)The standard way to make the near-equivalent to
a.reverse()would be via the prototype, like this:That does work in standard engines. So let’s look at what it does:
It gets the
prototypeproperty fromArray.It gets the
reverseproperty from the object it got in #1.It calls the function that property referenced using the
Function#callfeature of JavaScript function objects to makethisbe the argument you pass intocallduring 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.prototypewhen the new array is created. Soahas areverseproperty because its underlying prototype has areverseproperty.Doing
a.reverse()does this:Gets the
reverseproperty from theaobject. Since (normally)awon’t have its own property calledreverse, standard JavaScript property lookup looks toa‘s underlying prototype. It finds the property there and uses its value.Calls that function such that
thisisawithin the call.As you can see, the end result is the same provided that the underlying prototype of
aandArray.prototypestill refer to the same object. (It’s possible for them not to, although in the case ofArrayor any other built-in, if someone replaced [as opposed to augmenting]Array.prototype, that would be a Bad Thing(tm).)