01
"Inheritance" can be used with Objecs and classes
code below shows inefficent code,
DON't make duplicate code like the talk() method in both objects
const me = { talk(){ return 'Talking' } } const you = { talk(){ return 'Talking' } }
me.talk() you.talk()
02
DON'T Duplicate!
Make a prototype (object or class)
Create methods and properties and incorporate
Inheritance from those prototypes into 'instances' of that classes or objects.
classes
class Person { talk(){ return 'talking' } } const me = new Person() const you = new Person()
me.talk() you.talk()
Now the method "inherits" from the talk()
method from the Person
class
03
Now, We can re-assign a new method to the instance of the Person
class, and it will Not change the talk() method within Person
class Person{ talk(){ return 'Talking' } } const me = new Person() function newMethod(){ return 'new Method' } me.talk = newMethod() me.talk
Person
04
Remember that including () after a function when assigning
it to a variable will only asign the Return Value, if you do that you can not invoke the
method on the instance of the class because me.talk will only have the
return value 'new Method' from the newMethod function.
so invoking the talk() method on
the me instance with () will throw an error
class Person{
talk(){
return 'Talking'
}
}
const me = new Person()
function newMethod(){
return 'new Method'
}
me.talk = newMethod
me.talk()
me.talk = newMethod()
me.talk()
05
If you console the me instance, we used to see that any method from the
class would reside in __proto__, but this is now depreciated, see next lesson to
continue to
and see in modern javascript using [[Prototype]]
06
Notice, Methods are not in the instance itself, they are in
the [[Protoype]] of it's parent class Person.
class Person{
talk(){
return 'Talking'
}
}
const me = new Person()
me
07
But we can add attributes to the instance itself
class Person{
talk(){
return 'Talking'
}
}
const me = new Person()
me.age = 30
me