简体   繁体   中英

prototypical reusability in javascript explaination

I am confuse bit by going through multiple website tutorials and now can't find the difference between below two statements; (Suppose Person a super class/function of Employee)

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

As i know first line show an Employee REFERENCE pointed to Person constructor. And constructor of Person was created by . 创建的。 And Second is simply created a Employee constructor.

Let me know if am right as am a java programmer and found javascript is confusing.

The prototype in javascript is like classes in java. So the code:

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

Means:

class Employee inherits new Person() { // meaning of first line
    Employee constructor = Employee    // meaning of second line
}

In classical javascript, there are no classes, instead there are constructors. And a constructor is just a regular function that you call via new myFunction() instead of myFunction() .

And instead of a constructor belonging to a class, in javascript a prototype (class-like object) is a property of a constructor. And yes, functions are objects just like any other thing in javascript so they can have properties just like any other object.

Also, in javascript constructors cannot inherit from constructors (don't be silly :D ). Instead, constructors inherit from objects (strictly speaking, objects inherit from objects since the inheritance happens when you call the constructor). That's why we create an instance of the superclass object - to make it an object so we can inherit.

Technically speaking, the line Employee.prototype.constructor is not necessary. The first line is all that's needed to set up inheritance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM