JavaScript Prototypes and Inheritance
What is a prototype?
An object that exists on every function in JavaScript
Object's __proto__ is _____
null
What is this an example of? function Animal(voice){ this.voice = voice || 'grunt' } function Cat(name,color){ Animal.call(this,'Meow') this.color=color;this.name=name } Cat.prototype = Object.create(Animal.prototype) Cat.prototype.constructor = Cat
Inheritance
Add an age property to the Cat function's prototype function Cat(name,color){this.name=name;this.color=color}
Cat.prototype.age = 3
T/F a prototype is a class
False. It is an object
T/F Objects have a prototype property
False. Objects have a __proto__property
By default, all objects in javascript inherit from ____
Object
JavaScript inheritance is done through ____
Prototypes
I want to easily be able to get the last element of an array by doing myArray.last. This doesn't exist as a function of normal arrays in JavaScript. How could I do this?
Use prototypes to add a new function property to the array prototype Object.defineProperty(Array.prototype,'last', {get:function(){ this[this.length-1]; });