一、对象的基本形式
1.除了原始值(基本类型),其他(函数、数组)都是对象
基础数据类型:Number、String、Boolean、Undefined、Null、Symbol。
2.语法
var car = {
color: 'red', //键值对
height: 1.8,
start: function () {
console.log('‘启动');
},
stop: function () {
console.log('熄火');
},
suv: true,
luntai:[1,2,3,4]
};
- 在对象⾥的函数叫⽅法(methods)
- 对象里包含属性与值,属性的值可以是任意类型的
二、js对象中的常规操作
var car = {
color: "red",
height: 1.5,
start: function () {
console.log("启动");
},
end: function () {
console.log("熄火");
},
};
car.color = "blue"; //改
car.suv = true; //增
delete car.height; //删
console.log(car.color); //查
也可以使用方括号 [] 进行操作(不常用,比较复杂)
var car = {
color: "red",
height: 1.5,
start: function () {
console.log("启动");
},
end: function () {
console.log("熄火");
},
};
car["color"] = "blue"; //改
car["suv"] = true; //增
delete car["height"]; //删
console.log(car["color"]); //查
三、怎么访问自身属性
可以通过 this 调用自身的属性和方法
var car = {
color: "red",
height: 1.5,
start: function () {
console.log("启动");
},
end: function () {
console.log("熄火" + this.color);
},
};
car.end();
四、创建对象的方式
1.直接声明一个对象并赋值
var car1 = new Object();
car1.color = "red";
car1.height = 1.9;
console.log(car1);
2.自定义构造函数
function Factory(color, height, suv) {
this.color = color;
this.height = height;
this.suv = suv;
}
var car1 = new Factory("red", 1.8, true);
console.log(car1);