function Dog(name, age){
this.name = name;
this.age = age;
this.bark = function(){
console.log(this.name + " just barked!");
}
}
new
keyword¶Object.__proto__ === Constructor.prototype
var rusty = new Dog("Rusty", 10);
rusty.name;
rusty.age;
rusty.bark();
Constructor function
function Car(make, model, year){
this.make = make;
this.model = model;
this.year = year;
this.numWheels = 4;
}
Refactor: using call
function Motorcycle(make, model, year){
// borrow properties from Car
Car.call(this, make, model, year)
this.numWheels = 2;
}
Refactor: using apply
function Motorcycle(make, model, year){
Car.apply(this, [make,model,year]);
this.numWheels = 2;
}
Refactor: even better using apply with arguments
function Motorcycle(){
Car.apply(this, arguments);
this.numWheels = 2;
}
Exercise: Constructor Function
PART 1
Create a constructor function for a Person, each person should have a firstName, lastName, favoriteColor and favoriteNumber. Your function MUST be named Person.
function Person(firstName, lastName, favoriteColor, favoriteNumber){
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteNumber = favoriteNumber;
}
Add a method called multiplyFavoriteNumber to the constructor function that takes in a number and returns the product of the number and the object created from the Person functions' favorite number.
function Person(firstName, lastName, favoriteColor, favoriteNumber){
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteNumber = favoriteNumber;
this.multiplyFavoriteNumber = function(num){
return num * this.favoriteNumber;
}
}
PART 2
Given the following code:-
function Parent(firstName, lastName, favoriteColor, favoriteFood){
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteFood = favoriteFood;
}
function Child(firstName, lastName, favoriteColor, favoriteFood){
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteFood = favoriteFood;
}
Refactor the Child function to remove all the duplication from the Parent function. You should be able to remove 4 lines of code in the Child function and replace it with 1 single line.
if use call, have to pass in all of this arguments separted by commas
function Child(){
Parent.apply(this, arguments);
}
Anytime an object is created using the 'new' keyword, a property called "__proto__" gets created, linking the object and the prototype property of the constructor function
prototype: found in constructor function __proto__: found in created object
Peson.prototype.constructor === Person
elie.__proto__ === Person.prototype
This is the constructor function
function Person(name){
this.name = name;
}
In Javascript, every function has a property on it called prototype (auto created) Person.prototype
Create 2 new objects from the Person constructor
var elie = new Person("Elie"); //__proto__ is created from new keyword
var colt = new Person("Colt");
The 'new' keyword will add __proto__ to the object created. Dunder proto will point to the prototype property of the Person constructor
elie.__proto__ === Person.prototype;
colt.__proto__ === Person.prototype;
The Person.prototype object has a property called constructor which points back to the function
Person.prototype.constructor === Person;
remember arr.proto === Array.prototype
var arr = []; //short hand of
var arr = new Array; //Array: built-in constructor function
arr.push; //where is the method located?
console.dir(arr); //find in __proto__ of Array
arr.hasOwnProperty('length');
dir(arr); //find in __proto__ of Object
monkey patching
). It's also recommended that you do not add properties to the Object.prototype as that can have some pretty bad side effects.function Vehicle(make, model, year){
this.make = make;
this.model = model;
this.year = year;
this.isRunning = false;
}
Put methods inside prototype
Vehicle.prototype.turnOn = function(){
return this.isRunning = true;
}
Vehicle.prototype.turnOff = function(){
return this.isRunning = false;
}
Vehicle.prototype.honk = function(){
if (this.isRunning){
return "beep";
}
}
Exercise: Prototypes
1 - Create a constructor function for a Person. Each person should have a firstName, lastName, favoriteColor, favoriteNumber)
function Person(firstName, lastName, favoriteColor, favoriteNumber){
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteNumber = favoriteNumber;
}
2 - Add a function on the Person.prototype called fullName that returns the firstName and lastName property of an object created by the Person constructor concatenated together.
Examples:
var person = new Person("Elie", "Schoppik", "purple", 34)
person.fullName() // "Elie Schoppik"
Person.prototype.fullName = function(){
return this.firstName + " " + this.lastName;
}
3 - Add a property on the object created from the Person function called family which is an empty array. This will involve you adding an additional line of code to your Person constructor.
this.family = []
: not add to prototype object because we don't want this to be shared by every object created by the Person constructor function when the new keyword is used
function Person(firstName, lastName, favoriteColor, favoriteNumber){
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteNumber = favoriteNumber;
this.family = [];
}
4 - Add a function on the Person.prototype called addToFamily which adds an object constructed from the Person constructor to the family array. To make sure that the object you are adding is an object construced from the Person constructor (HINT - take a look at the instanceof keyword). Make sure that your family array does not include duplicates! This method should return the length of the family array.
Examples:
var person = new Person("Elie", "Schoppik", "purple", 34)
var anotherPerson = new Person()
person.addToFamily(anotherPerson); // 1
person.addToFamily(anotherPerson); // 1
person.family.length // 1
person.addToFamily("test"); // 1
person.addToFamily({}); // 1
person.addToFamily([]); // 1
person.addToFamily(false); // 1
person.family.length // 1 */
Person.prototype.addToFamily = function(){
if (arguments[0] instanceof Person){
this.family.push(arguments[0]);
}
return this.family.length;
}
Person.prototype.addToFamily = function(person){
//this.family.indexOf(person) === -1: ensure person not in the family array
if(this.family.indexOf(person) === -1 && person instanceof Person){
this.family.push(person)
}
return this.family.length;
}
PART II
1 - Implement your own version of Array.prototype.map. The function should accept a callback and return a new array with the result of the callback for each value in the array.
Array.prototype.map = function(callback){
var newArr = [];
for(var i = 0; i < this.length; i++){
newArr.push(callback(this[i], i, this))
}
return newArr;
}
To use the function
[1,2,3].map(function(val){
return val;
});
2 - Implement a function called reverse that reverses a string and place it on the String.prototype
Examples:
"test".reverse() // "tset"
"tacocat".reverse() // "tacocat"*/
String.prototype.reverse = function(){
return this.split("").reverse().join("");
}
Alternative
String.prototype.reverse = function(){
var newStr = "";
//loop backwards from the last char of string
for (var i=this.length-1; i>=0; i--){
newStr += this[i];
}
return newStr;
}
Obj.prototype.constructor === Obj
obj.create
overwrite the constructor propertyObject reference <> Inheritance
- We can't assign one object to another
Obj1 = Obj2
- it will just create a reference!- No new objects is created here! obj2 is just a link to obj1
- This means that if we change the prototye (properties & methods) of Obj1, it will affect prototype of Obj2
var parent = {name: "Elie"};
var child = parent;
child.name = "Tim";
parent.name
The correct way...
object.create
constructor
propertyParent constuctor function
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
Child constructor function
function Student(firstName, lastName){
Person.apply(this, arguments);
}
Create object by copying prototype which overwrite the prototype.constructor` of Student!
Student.prototype = Object.create(Person.prototype);
Student link to person constructor (wrong!)
Student.prototype.constructor;
Reset the constructor property
Student.prototype.constructor = Student;
Add a new method to Student (child)
Student.prototype.status = function(){
return "I am currently a student"
}
Create a new Person object (parent)
var elie = new Person('Elie', 'Schoppik');
Cannot find method status in Person (parent)
elie.status; // undefined
How about using 'new'?
Exercise: Inheritance
1 - Create a constructor function for a Vehicle. Each vehicle should have a make, model and year property.
function Vehicle(make, model, year){
this.make = make;
this.model = model;
this.year = year;
}
2 - Add a function to the Vehicle prototype called start which returns the string "VROOM!"
Vehicle.prototype.start = function(){
return "VROOM!";
}
3 - Add a function to the Vehicle prototype called toString which returns the string "The make, model, and year are" concatenated with the make, model and year property
Examples
var vehicle = new Vehicle("Tractor", "John Deere", 1999)
vehicle.toString() // 'The make, model, and year are Tractor John Deere 1999'
Vehicle.prototype.toString = function(){
return "The make, model, and year are " + this.make + " " + this.model + " " + this.year;
}
4 - Create a constructor function for a Car. Each object created from the Car function should also have a make, model, and year and a property called numWheels which should be 4. The Car prototype should inherit all of the methods from the Vehicle prototype
function Car(){
Vehicle.apply(this, arguments);
this.numWheels = 4;
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
5 - Create a constructor function for a Motorcycle. Each object created from the Motorcycle function should also have a make, model, and year and a property called numWheels which should be 2. The Motorcycle prototype should inherit all of the methods from the Vehicle prototype
function Motorcycle(){
Vehicle.apply(this, arguments);
this.numWheels = 2;
}
Motorcycle.prototype = Object.create(Vehicle.prototype);
Motorcycle.prototype.constructor = Motorcycle;