- Define methods on custom objects by attaching them to the prototype
- Fork and clone this repository.
- Change to the new directory.
- Install dependencies.
- Create and checkout a new branch,
training
In the previous lesson, we saw how to use constructors to de-duplicate effort in creating new objects that share attributes. We learned that we should never define a method inside a constructor function. So how should we get behavior in our custom objects?
Remember wonderWoman
?
const wonderWoman = {
name: 'Diana Prince',
alias: 'Wonder Woman',
usePower: function() {
return 'Deflects bullets with bracelets'
}
}
We made a nice Hero
constructor to take care of the attributes .
const Hero = function(name, alias, power) {
this.name = name
this.alias = alias
this._power = power
}
- Create
usePower
and attach it to the constructor function's prototype. - Create a method to say the hero's name and alias. Attach it to the prototype.
- Create
batman
andwonderWoman
. Call the method just attached. - Observe that this method isn't part of objects created using the constructor function.
Change the run tracker code you made in the previous lesson to use prototypes.
- All content is licensed under a CCBYNCSA 4.0 license.
- All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact legal@ga.co.