views:

59

answers:

2
function Person(name) {
    this.name = name;
    this.say = function() {
        console.info('I am ' + this.name);
    }
}
var p=new Person('stackoverflow');

Someone tell me that the above codes are equals to :

function Person(name) {
    this.name = name;
    this.say = function() {
        console.info('I am ' + this.name);
    }
}

var p={};
Person.call(p,'stackoverflow');

Is this true?

If so, how about the prototype?

Each object in javascripte owns a prototype,and the prototype chain hold the releationship of the obejcts,I wonder if this prototype does something or not.

In this example, when the object of 'p' is created,does it call some build-in method of the superclass of Person?

BTW,what I want to know is what does the syntax var p=new Person('stackoverflow'); do ?


-----------------update------------------

function Person(name) {
    this.name = name;
}
Person.prototype.say = function() {
    console.info('I am ' + this.name);
}

How about if I put the defination of say inside the person function:

function Person(name) {
    this.name = name;
    Person.prototype.say = function() {
        console.info('I am ' + this.name);
    }
}
+2  A: 

The code:

var p=new Person('stackoverflow');

creates a new instance of the Person class. You must remember that classes in javascript are functions, so when you call:

Person.call(p,'stackoverflow');

You are just calling the Person function and binding it to the p object (this means that in the function context the this will refer to the p object). Those pieces of code do the same thing, except for the fact that the first is an instance of the class so if you update the prototype object of person its properties will be updated.

Anyway the situation is different when you fill the prototype object of the Person function:

Person.prototype={test:"test"}

If you add this after the Person function declaration you will see that those pieces of code have a different behaviour. The object initialized with "new" will contain the test property, but the other one hasn't it. This happens because the prototype object is applied only to the instances of the class when using "new".

mck89
That's to say,the first p owns the prototype of Person?
hguser
Yes because it's an instance of Person and every property of the prototype of Person is applied to the object. Add `Person.prototype={test:"test"};` and test with firbug with console.dir(p) in both cases and you'll see the difference.
mck89
Thank, I test it and I know it now.:) BTW,is there any plugin in eclipse which can run javascript directly and standalone?
hguser
A: 

Well, actually

var p=new Person('stackoverflow');

is equivalent to:

var p={};
p.__proto__ = Person.prototype;
Person.call(p,'stackoverflow');

except that __proto__ is not standard JavaScript (but is supported by some implementations).

Edgar Bonet