JavaScript/OOP-classical/Exercises
Appearance
Topic: OOP - 1
1. Create an object with (minimum) two different techniques. The object shall contain information about a person: first name, family name, hobbies, address, weight, ...
Click to see solution
"use strict";
// Example 1: literals
const john = {
firstName: "John",
familyName: "Ghandi",
hobbies: ["Reading books", "Travel"],
address: {
city: "Dakkar",
street: "Main Road 55"
},
weight: 62
};
console.log(john);
// Example 2: 'new' operator plus direct assignment of a property
const jim = new Object(
{
firstName: "John",
familyName: "Ghandi",
hobbies: ["Reading books", "Travel"],
weight: 62
});
jim.address =
{
city: "Dakkar",
street: "Main Road 55"
};
console.log(jim);
// Example 3: 'Object.create' method
const linda = Object.create(
{
firstName: "Linda",
familyName: "Ghandi"
}); // ... and more properties
console.log(linda);
2. Create an object 'Car' in a way that you can create an instance with const myCar = new Car("Tesla", "Model S");
Click to see solution
"use strict";
function Car(brand, model) {
this.brand = brand
this.model = model;
this.show = function () {return "My car is a " + this.brand + " " + this.model};
}
const myCar = new Car("Tesla", "Model S");
console.log(myCar.show());
3. Create an object 'myBike' and an object 'myEBike' as its sub-object in a hierarchy.
Click to see solution
"use strict";
// Example 1
const myBike = Object.create(
{
frameSize: "52",
color: "blue"
});
const myEBike = {power: "500 Watt"};
// define hierarchy
Object.setPrototypeOf(myEBike, myBike);
console.log(myEBike);