// Parent class
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log("Hello. My name is " + this.name);
};
Person.prototype.sayGoodbye = function() {
console.log("Goodbye!");
};
// Child class
function Student(name, gpa) {
Person.call(this, name);// I'm confused what does keyword 'this' refer to?
this.gpa = gpa;
}
// create child object
let john = new Student("john",3.5);
Does the keyword 'this' refer to object john or Person.prototype?
The new operator preceding Student("john",3.5); creates a new instance object, prototyped on the following function's prototype property, before calling the function with the newly created object as its this value. ( Refer to new operator documentation on MDN for more detail).)
So the this in
Person.call(this, name);
is the student object created and returned by new before being stored in the john variable.
Student code then calls the Person function with its own this value so that the Person constructor can add "Person" type properties to the Student object before returning from Student.
Worth noting:
The example shows how the construction of class objects was undertaken before implementation of the class keyword in JavaScript
This particular example does not implement inheritance of Person.prototype properties by Student objects. This was sometime implemented using a dummy Person object as the prototype of Student, using code similar to:
Student.prototype = new Person();
Student.prototype.constructor = Student;
The shortcomings and limitations of this practice at least contributed to the introduction of class constructor functions in ECMAScript.
Here to make Student a child class you need to extend it to the Person class:
class Person {
var name;
constructor(name) {
this.name = name;
}
sayhello(){
console.log("Hello. My name is " + this.name);
}
sayGoodbye(){
console.log("Goodbye!");
}
}
class Student extends Person {
getName(){
return this.name;
}
}
student = new Student("Jhon");
The 'this' keywords refers to the current object. You can call methods of the parent class from the child class using the child class object itself as you are using extend keywords.
This is a simple example of inheritance.
Related
My proto reference of "mike" instance points to "Student" but as its name shows "Person" , I don't know why is that. Here is my code and screenshot of console below:
const Person = function (firstName,birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
}
Person.prototype.calcAge = function () {
console.log(2037 - this.birthYear);
}
const Student = function (firstName, birthYear, course){
Person.call(this,firstName,birthYear);
this.course = course;
};
Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student;
Student.prototype.introduce = function () {
console.log(`My name is ${this.firstName} and ,I study ${this.course}`);
}
const mike = new Student('Mike',2020, 'Computer Science');
console.log(mike);
When I check on console it shows Person:
Student.prototype = Object.create(Person.prototype)
In this case, you are creating a new object and make it the value of Student.prototype. The new object Student has Person.prototype as its prototype.
The very first thing you see in Chrome's console is Student. That is the "type" of your mike object.
On the other hand, the __proto__ property of mike references the prototype from which this instance was created. Your code has explicitly defined that prototype with the following statement:
Student.prototype = Object.create(Person.prototype);
So, from that moment on, Student.prototype instanceof Person is true, but Student.prototype instanceof Student false. And all instances created with new Student, will reference the Student.prototype in their __proto__ property. So what you see is as expected.
The fact that the following assignment was made, doesn't change this behaviour:
Student.prototype.constructor = Student;
This is a cosmetic change, and doesn't determine the nature of the instances that Student creates. That might have mislead you.
class syntax
The code you provided performs the steps needed to set up a prototype chain, where a Student inherits from a Person.
In modern JavaScript it is much less cryptical to make this happen. Nowadays you would write this example as follows:
class Person {
constructor(firstName,birthYear) {
this.firstName = firstName;
this.birthYear = birthYear;
}
calcAge() {
console.log(2037 - this.birthYear);
}
}
class Student extends Person {
constructor(firstName, birthYear, course) {
super(birthYear, course);
this.course = course;
}
introduce() {
console.log(`My name is ${this.firstName} and ,I study ${this.course}`);
}
}
const mike = new Student('Mike',2020, 'Computer Science');
console.log(mike);
The result in the console will also here confirm that the prototype object of a Student instance is an instance of Person (not of Student).
I've a simple example from MDN.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(this.name + ' barks.');
}
}
let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
Now, in subclass Dog how does this.name works under the hood. Since this refers to Dog class instance and name is not something which exists on Dog instance. So to access that we use super call which invokes parent's constructor. I get that it looks up.
But can someone please explain via the prototype mechanism (I'm comfortable in understanding the prototype lookup and chaining mechanism).
I'm sure deep down it will boil down to that but not clear about intermediate steps in between. Thanks!
this refers to Dog class
No, this refers to the instantiated object. The instantiated object has an internal prototype of Dog.prototype, and Dog.prototype has an internal prototype of Animal.prototype.
Since this refers directly to the instantiated object (in both constructors, and in all of the methods),
this.name = name;
puts the name property directly on that object, so it's completely fine to reference d.name, or, inside one of the methods, this.name:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(this.name + ' barks.');
}
}
const d = new Dog('Mitzie');
const dProto = Object.getPrototypeOf(d);
const secondProto = Object.getPrototypeOf(dProto);
console.log(dProto === Dog.prototype);
console.log(secondProto === Animal.prototype);
console.log(d.hasOwnProperty('name'));
Actually, what I wanted to ask was under the hood. So, here's the answer based on #Jai's pointer in comments that I was looking for.
I ran the class based code through es5compiler or any compiler and got this conversion
var Dog = /** #class */ (function (_super) {
__extends(Dog, _super);
function Dog(name) {
return _super.call(this, name) || this;
}
Dog.prototype.speak = function () {
console.log(this.name + ' barks.');
};
return Dog;
}(Animal));
So basically
return _super.call(this, name) inside Dog function explains the confusion of this reference inside speak method of class Dog. It changes the context through call()
I'm trying to understand what actually happens when you create a new instance of a class with ES6. As far as I can tell, a new instance is created with properties as defined in the constructor and then the rest of the methods in the class are actually properties on the prototype object
For example
class Dog {
constructor(name){
this.name = name
}
speak (){
console.log('Woof')
}
}
Would be the equivelant to
function Dog(name){
this.name = name;
}
Dog.prototype.speak = function () {
console.log('Woof');
}
In the class example. If I create an instance of my Dog class, Is the prototype of that method pointing to the Dog class itself or is it a completely new object? Because when I Object.getPrototypeOf(myDog) it returns Dog {}.
They are functionally exactly the same. Here are some interesting properties about prototypes and classes to point out though:
class Dog1 {
constructor(name){
this.name = name
}
speak (){ // adds speak method to the prototype of Dog1
console.log('Woof')
}
}
Dog1.prototype.speak = () => { // overwrites speak method to the prototype of Dog1
console.log('Different Woof');
}
console.log(typeof Dog1); // Class keyword is just syntactic sugar for constructor function
const newDog = new Dog1('barkie');
newDog.speak();
/////////////////////////////
function Dog2(name){
this.name = name;
}
Dog2.prototype.speak = () => {
console.log('Woof');
}
const aDog = new Dog2('fluffy');
aDog.__proto__.speak(); // the __proto__ property references the prototype
aDog.speak(); // the __proto__ property is not necessary, it will automatically climb the protochain if the property is not found on the object itself.
I left some comments in order to point out the quirks which can be a bit hard to grasp. I you have any further questions about it you can leave a comment. Hopefully this is helpful to you.
Example taken from here: http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/
I also asked a similar question here: Javascript: Added function does not appear on parent object.
Create an object
>function Person(name) {
this.name = name;
}
Add an attribute as a prototype. The new kind attribute does not appear on the object.
>Person.prototype.kind = 'person'
>Person
<function Person(name) {
this.name = name;
}
Now create a new object using the parent as the prototype. The added attribute is visible.
var zack = new Person('Zack');
Person {name: "Zack", kind: "person"}
Why is the added kind attribute not visible on the parent Person object, even though it can convey it to children?
This is beceause Person is just a funtion(object)/Constructor:
Person =
function Person(name) {
this.name = name;
}
To Get the kind object on person refer to the prototype
Person.prototype =
Person {kind: "person"}
Im not an expert in this but if you would want to create a new constructor you should overwrite the function.
You could see the function (below) as an constructor to set instance specific variables
function Person(name) {
this.name = name;
}
Person.prototype.kind = 'person' is like a static variable on the class
You are looking at the Person Constructor.
To look at the properties of the definition of a Person you can use Object.getOwnPropertyNames(Person.prototype)
This would show the kind property.
Quite recently I read about JavaScript call usage in MDC
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
one linke of the example shown below, I still don't understand.
Why are they using inheritance here like this
Prod_dept.prototype = new Product();
is this necessary? Because there is a call to the super-constructor in
Prod_dept()
anyway, like this
Product.call
is this just out of common behaviour? When is it better to use call for the super-constructor or use the prototype chain?
function Product(name, value){
this.name = name;
if(value >= 1000)
this.value = 999;
else
this.value = value;
}
function Prod_dept(name, value, dept){
this.dept = dept;
Product.call(this, name, value);
}
Prod_dept.prototype = new Product();
// since 5 is less than 1000, value is set
cheese = new Prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
car = new Prod_dept("honda", 5000, "auto");
Thanks for making things clearer
The answer to the real question is that you need to do both:
Setting the prototype to an instance of the parent initializes the prototype chain (inheritance), this is done only once (since the prototype object is shared).
Calling the parent's constructor initializes the object itself, this is done with every instantiation (you can pass different parameters each time you construct it).
Therefore, you should not call the parent's constructor when setting up inheritance. Only when instantiating an object that inherits from another.
Chris Morgan's answer is almost complete, missing a small detail (constructor property). Let me suggest a method to setup inheritance.
function extend(base, sub) {
// Avoid instantiating the base class just to setup inheritance
// Also, do a recursive merge of two prototypes, so we don't overwrite
// the existing prototype, but still maintain the inheritance chain
// Thanks to #ccnokes
var origProto = sub.prototype;
sub.prototype = Object.create(base.prototype);
for (var key in origProto) {
sub.prototype[key] = origProto[key];
}
// The constructor property was set wrong, let's fix it
Object.defineProperty(sub.prototype, 'constructor', {
enumerable: false,
value: sub
});
}
// Let's try this
function Animal(name) {
this.name = name;
}
Animal.prototype = {
sayMyName: function() {
console.log(this.getWordsToSay() + " " + this.name);
},
getWordsToSay: function() {
// Abstract
}
}
function Dog(name) {
// Call the parent's constructor
Animal.call(this, name);
}
Dog.prototype = {
getWordsToSay: function(){
return "Ruff Ruff";
}
}
// Setup the prototype chain the right way
extend(Animal, Dog);
// Here is where the Dog (and Animal) constructors are called
var dog = new Dog("Lassie");
dog.sayMyName(); // Outputs Ruff Ruff Lassie
console.log(dog instanceof Animal); // true
console.log(dog.constructor); // Dog
See my blog post for even further syntactic sugar when creating classes. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
Technique copied from Ext-JS and http://www.uselesspickles.com/class_library/ and a comment from https://stackoverflow.com/users/1397311/ccnokes
The ideal way to do it is to not do Prod_dept.prototype = new Product();, because this calls the Product constructor. So the ideal way is to clone it except for the constructor, something like this:
function Product(...) {
...
}
var tmp = function(){};
tmp.prototype = Product.prototype;
function Prod_dept(...) {
Product.call(this, ...);
}
Prod_dept.prototype = new tmp();
Prod_dept.prototype.constructor = Prod_dept;
Then the super constructor is called at construction time, which is what you want, because then you can pass the parameters, too.
If you look at things like the Google Closure Library you'll see that's how they do it.
If you have done Object Oriented Programming in JavaScript, you will know that you can create a class as follows:
Person = function(id, name, age){
this.id = id;
this.name = name;
this.age = age;
alert('A new person has been accepted');
}
So far our class person only has two properties and we are going to give it some methods. A clean way of doing this is
to use its 'prototype' object.
Starting from JavaScript 1.1, the prototype object was introduced in JavaScript. This is a built in object that
simplifies the process of adding custom properties and methods to all instances of an object.
Let's add 2 methods to our class using its 'prototype' object as follows:
Person.prototype = {
/** wake person up */
wake_up: function() {
alert('I am awake');
},
/** retrieve person's age */
get_age: function() {
return this.age;
}
}
Now we have defined our class Person. What if we wanted to define another class called Manager which inherits some properties from Person. There is no point redefining all this properties again when we define our Manager class, we can just set it to inherit from the class Person.
JavaScript doesn't have built in inheritance but we can use a technique to implement inheritance as follows:
Inheritance_Manager = {};//We create an inheritance manager class (the name is arbitrary)
Now let's give our inheritance class a method called extend which takes the baseClass and subClassas arguments.
Within the extend method, we will create an inner class called inheritance function inheritance() { }. The reason why we are using this inner
class is to avoid confusion between the baseClass and subClass prototypes.
Next we make the prototype of our inheritance class point to the baseClass prototype as with the following code:
inheritance.prototype = baseClass. prototype;
Then we copy the inheritance prototype into the subClass prototype as follows: subClass.prototype = new inheritance();
The next thing is to specify the constructor for our subClass as follows: subClass.prototype.constructor = subClass;
Once finished with our subClass prototyping, we can specify the next two lines of code to set some base class pointers.
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
Here is the full code for our extend function:
Inheritance_Manager.extend = function(subClass, baseClass) {
function inheritance() { }
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}
Now that we have implemented our inheritance, we can start using it to extend our classes. In this case we are going to
extend our Person class into a Manager class as follows:
We define the Manager class
Manager = function(id, name, age, salary) {
Person.baseConstructor.call(this, id, name, age);
this.salary = salary;
alert('A manager has been registered.');
}
we make it inherit form Person
Inheritance_Manager.extend(Manager, Person);
If you noticed, we have just called the extend method of our Inheritance_Manager class and passed the subClass Manager in our case and then the baseClass Person. Note that the order is very important here. If you swap them, the inheritance
will not work as you intended if at all.
Also note that you will need to specify this inheritance before you can actually define our subClass.
Now let us define our subClass:
We can add more methods as the one below. Our Manager class will always have the methods and properties defined in the Person class because it inherits from it.
Manager.prototype.lead = function(){
alert('I am a good leader');
}
Now to test it let us create two objects, one from the class Person and one from the inherited class Manager:
var p = new Person(1, 'Joe Tester', 26);
var pm = new Manager(1, 'Joe Tester', 26, '20.000');
Feel free to get full code and more comments at:
http://www.cyberminds.co.uk/blog/articles/how-to-implement-javascript-inheritance.aspx