
There is a syntax called class
.
This is a grammar that helps to create a cool inheritance function using constructor
and prototype
.
There is not much difference in terms of syntax and function from the existing function
, and it is just slightly easier to see.
Let’s take a closer look at how to do it.
Create a constructor
machine implemented with the ES6 class
keyword
Everyone knows constructor
because we did it last time, right?
It was an object picking machine.
If you want to create a constructor
with the ES6 class
method, you can follow this.
class parent {
constructor() {
this.name = "Kim";
}
}
var child = new parent();
That’s it. This is the same syntax as the old function parent (){} something...
syntax for creating machines.
Now, using the new
keyword, you can create a new object in the machine called the parent you just created.
In the part where you write constructor()
, you can assign values to newly created objects by adding this.name
as before.
That’s it.
How do I add inheritable functions?
There are two ways I learned from doing sayHi
in the past.
-
How to add a function inside
constructor
likethis.sayHi
-
Was there a way to add it to the machine’s
prototype
?
▼ You can do the same thing as number 1, right?
class parent {
constructor() {
this.name = "Kim";
this.sayHi = function () {
console.log("hello");
};
}
}
var child = new parent();
Then the newly created child will have the sayHi()
function directly and can use it freely.
▼ To add to prototype
like number 2
class parent {
constructor() {
this.name = "Kim";
}
sayHi() {
console.log("hello");
}
}
var child = new parent();
You can do it like this.
Just like adding a function to an object.
Then the child can use the sayHi()
function in the parent’s prototype
when sayHi()
is written.
(Or you can just do parent.prototype.sayHi = function(){}
)
Note that Object.getPrototypeOf()
If you put an object in this function, it will output the parent prototype
.
This function tells you who the object inherits prototype
from.
You can see that it plays a similar role to the keyword __proto__
.
Add parameters inside constructor
To add parameters when creating a constructor
the ES6 way, you can do this:
class parnet {
constructor(n, a) {
this.name = n;
this.age = a;
}
}
var child = new parnet("Park", 30);
In this way, you can create a constructor
with parameters.
When creating a child, you can now enter two parameters.
Adding multiple functions in prototype
class parent {
constructor(n, a) {
this.name = n;
this.age = a;
}
sayHi() {
console.log("hi");
}
sayHello() {
console.log("hello");
}
}
var child = new parent("Park");
If you write like this, you can put several functions such as sayHi
and sayHello
in prototype
at the same time.
No big deal.