tags:

views:

54

answers:

3

If I have a class called Person.

var Person =  function(fname, lname){
    this.fname = fname;
    this.lname = lname;
}

Person.prototype.mname = "Test";
var p = new Person('Alice','Bob');

Now, p.__proto__ refers to prototype of Person but, when I try to do Person.__proto__, it points to function(), and Person.constructor points to Function().

Can someone explain what is the difference between function() and Function() and why the prototype of a Function() class is a function()?

A: 

The class called Person should be defined like this:

function Person (fname, lname){
    this.fname = fname;
    this.lname = lname;
}

Then you construct it like

 var person = new Person ("Betty", "Boo");
Kinopiko
yes that is right but I didn't get the answer to the my query
alter
There is no class ... only your mind
pst
A: 

When defining a function like this:

var Person = function (fname, lname){
    this.fname = fname;
    this.lname = lname;
}

This will make Person a function. A function is an object, which needs to be constructed like any other 'first class' object, so it has a constructor: the constructor of all function objects, called Function.

The prototype of all functions appears to be an object called function.

I like to refer to a nice explanation by Mike Koss that learned me a lot.

xtofl
Hey, I don't agree with Mike Koss. He has stated that, constructor property is part of the newly created object. "Note that in addition to the x and y properties that we created, our object has an additional property called constructor that points (in this case) to an internal JavaScript function." I think constructor property is not part of the newly created object. It is found by following person.__proto__.constructor. So if I redirect person.__prototype__ to null, then this person object will never be able to find its constructor.
alter
The article also mentioned that the `__proto__` field is not standard ecmascript, yet the `object.constructor` property seems to be standardized (cfr http://www.w3schools.com/jsref/jsref_constructor_boolean.asp)
xtofl
+1  A: 

Can someone explain what is the difference between function() and Function() and why the prototype of a Function() class is a function()?

__proto__ is an implementation-detail exposing the [[prototype]]. The [[prototype]] and the constructor need not be (are often not) the same thing. Anyway...

Consider this hypothesis: It is an impl. detail that depends on the engine -- and in the particular engine tested (FF, which version?), Function is an object which itself has a [[prototype]] of function. function is the primitive function-object. Person.prototype is (by default) of type function (the primitive function-object) and the assertions stated as a result of this apparent dichotomy. (JS has some quirks: new Number(0) is not the same as 0.)

However, this is not the case in IE(8). In IE the default prototype is a "plain object", not a function-object.

pst