2022.7.22 js对象

一、对象的基本形式

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值