Jump to content

JavaScript/OOP-classical/Exercises

From Wikibooks, open books for an open world

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: literalsconstjohn={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 propertyconstjim=newObject({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' methodconstlinda=Object.create({firstName:"Linda",familyName:"Ghandi"});// ... and more propertiesconsole.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";functionCar(brand,model){this.brand=brandthis.model=model;this.show=function(){return"My car is a "+this.brand+" "+this.model};}constmyCar=newCar("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 1constmyBike=Object.create({frameSize:"52",color:"blue"});constmyEBike={power:"500 Watt"};// define hierarchyObject.setPrototypeOf(myEBike,myBike);console.log(myEBike);
close