JavaScript/面向物件程式設計(經典)/練習
外觀
主題:面向物件程式設計 - 1
1. 使用(至少)兩種不同的技術建立一個物件。物件應包含關於一個人的資訊:名字,姓氏,愛好,地址,體重,...
點選檢視解決方案
"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. 以這種方式建立一個物件“汽車”,您可以使用 const myCar = new Car("Tesla", "Model S"); 建立一個例項
點選檢視解決方案
"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. 建立一個物件“我的腳踏車”和一個物件“我的電動腳踏車”作為其子物件,形成一個層次結構。
點選檢視解決方案
"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);