9
function f()
{
}

alert (f.prototype); // returns something like [object Object]

My understanding is by default the prototype of custom function should be null or undefined, can someone shed some light? thanks!

See also: How does __proto__ differ from constructor.prototype?

Community
  • 1
  • 1
nandin
  • 2,549
  • 5
  • 23
  • 27

3 Answers3

11

The prototype property of function objects is automatically created, is simply an empty object with the {DontEnum} and {DontDelete} property attributes, you can see how function objects are created in the specification:

Pay attention to the steps 9, 10 and 11:

9) Create a new object as would be constructed by the expression new Object().

10) Set the constructor property of Result(9) to F. This property is given attributes { DontEnum }.

11) Set the prototype property of F to Result(9). This property is given attributes as specified in 15.3.5.2.

You can see that this is true by:

function f(){
  //...
}

f.hasOwnProperty('prototype'); // true, property exist on f

f.propertyIsEnumerable('prototype'); // false, because the { DontEnum } attribute

delete f.prototype; // false, because the { DontDelete } attribute
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
7

Here is a link describing object inheritance:

http://javascript.crockford.com/prototypal.html

http://www.mollypages.org/misc/js.mp alt text
(source: mollypages.org)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • you mean every time you declare a function Foo, system or JavaScript engine will automatically create a Foo.prototype object for us? – nandin Feb 26 '10 at 20:13
  • 3
    @Ding: yes. That way when you create an object using your function as a constructor (`new f()`) the object you create will have Object in its prototype chain (because its prototype's prototype *is* Object). Be careful about confusing an object's prototype (the object it "inherits" from) with a function's `prototype` property - they're not the same thing. See CMS's answer for the gritty details if you're interested... – Shog9 Feb 26 '10 at 20:38
0

It's not undefined because you just defined it. Just because your function f() object is still empty doesn't mean it's not defined. It's just defined to have no contents.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794