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);