
One. prototype
is secretly created only for constructor
functions.
Even if you create a plain object
, array
, etc., there is no prototype
.
That’s it.
So what if you want to inherit something like a plain object
?
Either create a constructor
function.. Or use Object.create()
, as we will tell you next time, or class
, or one of the three.
2. If you want to find the genes of your parents, you can print __proto__
.
Child object
s created from the parent have a property called __proto__
.
If you print this out, the parent’s prototype
will be printed out.
So __proto__
has the same meaning as the parent’s prototype
.
Let’s print it out for real.
function machine() {
this.name = "Kim";
this.age = 15;
}
var student1 = new machine();
console.log(student1.__proto__);
console.log(machine.prototype);
student1.__proto__
machine.prototype
If you print out each one, does it come out the same?
Anyway, “__proto__
means the parent prototype
“.
You can just think of __proto__
as such a value that can be used when you want to genetically test what your parent’s gene is.
3. If you register __proto__
directly, you can implement inheritance function between object
.
__proto__
means prototype
of parent.
So what if we forcibly set a __proto__
on some object
?
Oh, there are parents like this.
It’s a kind of genetic engineering, let’s try it.
var parent = { name: "Kim" };
var child = {};
child.__proto__ = parent;
console.log(child.name);
Now we have created parent and child objects one by one.
And on the third line, we put the parent in the child’s __proto__
.
Then, the parent gene of the child becomes an object named { name : 'Kim' }
.
After that, the child is now free to use the child .name
property.
You can also implement the inheritance function like this.