JavaScript

OOP3: How new works

Student.prototype = new Person();
var student = new Student();

What’s the difference between above two?
Firstly, let’s see what new does.
1.create an object
2.set its _proto_ pointing to Person.prototype.
3.Person.apply(object, arguments)

In the first case, Student.prototype points to the object that can use all the methods and properties inherited from Person. While Student is a constructor function, not an object. It might work like this.

Student.prototype.a//get Person's this.a
//Student.a will get this.a in Student not the one in Person
Student.prototype.getA()//get Person's prototype function

In the second case, student is an instance, an object that can use all the methods and properties inherited from Student. It might work like this.

student.b//get Student's this.b
student.a
//get Student's prototype property which inherited from Person.prototype
student.getA();
//use Student's prototype function which inherited from Person.prototype

See, the instance invokes methods more straightforward.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s