对象
一、对象 和 属性
现实世界的 事物 是 包含很多属性的 对象。
属性 也可以是 包含其他属性的 对象。
二、创建对象:使用字面标记
let myCar = {
"brand": "Toyota",
"country": "Japan",
"price in China": 200000
};
// 访问对象的属性
console.log("访问对象的属性 'brand' 和 'price in China'");
console.log(myCar.brand);
console.log(myCar["price in China"]);
console.log("\n");
// 给对象添加属性
console.log("给对象添加属性 'productionDate'");
myCar.productionDate = "2020-1-1";
console.log(myCar);
console.log("\n");
// 修改对象的属性
console.log("修改对象的属性 'productionDate'");
myCar["productionDate"] = "2025-02-23";
console.log(myCar);
console.log("\n");
// 删除对象的属性
console.log("删除对象的属性 'productionDate'");
delete myCar.productionDate;
console.log(myCar);
console.log("\n");
// 函数作为对象的属性,也称之为对象的 方法
console.log("函数作为对象的属性");
myCar.showInfo = function () {
console.log(`brand: ${myCar.brand} - country: ${myCar.country} - price in China: ${this["price in China"]}`);
}
myCar.showInfo();
三、创建对象:使用构造函数
// 构造函数首字母大写
function Car(brand, country, priceInChina) {
this.brand = brand;
this.country = country;
this["price in china"] = priceInChina;
this.showInfo = function () {
console.log(`brand: ${myCar.brand} - country: ${myCar.country} - price in China: ${this["price in china"]}`);
}
}
let myCar = new Car("Toyota", "Japan", 200000);
console.log(myCar);
console.log(myCar["price in china"]);
myCar.showInfo();
三、原型 和原型链
内置构造函数 Object 创建对象
let myCar = new Object();
myCar.brand = "Toyota";
myCar.country = "Japan";
myCar["price in china"] = 200000;
函数本身也是对象
万物都是对象。
使用 原型 创建对象
let Car = {
brand: "汽车品牌",
country: "汽车厂商的国家",
"price in china": "在中国的售价"
}
//
let myCar = Object.create(Car);
console.log(myCar.brand);
console.log(myCar.country);
console.log(myCar["price in china"]);
let Car = {
type: "汽车",
hasTire: true
};
let ElectricCar = Object.create(Car);
ElectricCar.type = "电动车";
ElectricCar.hasBattery = true;
let myCar1 = Object.create(ElectricCar);
myCar1.owner = "jason";
let GasolineCar = Object.create(Car);
GasolineCar.type = "汽油车"
GasolineCar.hasEngine = true;
let myCar2 = Object.create(GasolineCar);
Object.prototype
js 中所有对象的原型链,最后都是终结于 Object.prototype。
四、构造函数 和 原型
function Car(price, owner) {
this.price = price;
this.owner = owner;
}
Car.prototype.type = "汽车";
Car.prototype.hasTire = true;
Car.prototype.price = "未知";
Car.prototype.showInfo = function () {
console.log(`车型: ${this.type} - 车主: ${this.owner} - 售价: ${this.price}`);
}
let myCar = new Car(200000, "jason");
function Car(price, owner) {
this.price = price;
this.owner = owner;
}
Car.prototype.type = "汽车";
Car.prototype.hasTire = true;
Car.prototype.price = "未知";
Car.prototype.showInfo = function () {
console.log(`车型: ${this.type} - 车主: ${this.owner} - 售价: ${this.price}`);
}
function ElectricCar(price, owner) {
Car.call(this, price, owner);
}
ElectricCar.prototype = Object.create(Car.prototype);
ElectricCar.prototype.type = "电动车"
ElectricCar.prototype.hasBattery = true;
ElectricCar.prototype.hasEngine = false;
let myCar = new ElectricCar(20000, "jason");