The accepted answer will definitely do the trick. And this โshortโ explanation turned into a leap, but hopefully it is useful.
There is one thing you should know about with the accepted answer. When you basically โinheritโ by doing Bar.prototype = new Foo() , you call the constructor. So, if you have code in your constructor that will not be used as a launch pad for another "class", you will come across strange effects. Take for example:
var Person = function (firstName, lastName) { .... }; var Student = function (firstName, lastName, grade) { .... };
Let's say Student is an extension of Person . How are you going to create a prototype on Student ? Probably not like Student.prototype = new Person("John", "Doe");
Another processing method, which is a bit more complicated, but can be wrapped inside another function, is as follows:
var extend = function (child, parent) { var f = function () {}; f.prototype = parent.prototype; child.prototype = new f(); child.prototype.constructor = parent; } var Person = function (firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } Person.prototype.getName = function () { return this.firstName + " " + this.lastName; } Person.prototype.setAge = function (age) { this.age = age; } var Student = function (firstName, lastName, grade) { Person.call(this, firstName, lastName); this.grade = grade; }; extend(Student, Person);
This gives you not only the functionality of Person, but also allows you to build . It looks like what you are actually doing with inheritance.
How it works? Great question. First, objects are assigned around [mostly] by reference. The prototype is an object. So, in the extend function, I create an empty function that will serve as a surrogate for child . This copies the parent prototype for itself, and then creates a new instance of the child prototype itself. Thus, the parent constructor is not called, but the original prototype is still in use. To make sure instanceof still works, child.prototype.constructor set to parent - it effectively informs javascript that the thing the child came from is a parent, not a surrogate.
In addition, when overriding methods, you can use the "class" that you inherit from the prototype method, and apply or call it with this -, which starts the method with the scope of the current object, and you can pass any arguments that you feel, but they are accepted by your chosen function. For example, Person.prototype.getName.apply(this); runs Person getName in the context of the current instance of the student. Suppose we wanted to override setAge to just console.log to print the age.
Student.prototype.setAge = function () { Person.prototype.setAge.apply(this, arguments); console.log(this.age); }
This is where the Person setAge with the arguments that were passed to Student setAge . Thus, it basically allows you to transfer material without having to know about the details of the original arguments of the method.