当前位置:网站首页>2022.7.22 JS object

2022.7.22 JS object

2022-07-23 21:10:00 The secret of longevity is sleep

One 、 Basic form of object

1. In addition to the original value ( Basic types ), other ( function 、 Array ) Are all objects

        Basic data type :Number、String、Boolean、Undefined、Null、Symbol.

2. grammar

var car = {
  color: 'red', // Key value pair 
  height: 1.8,
  start: function () {
    console.log('‘ start-up ');
  },
  stop: function () {
    console.log(' Stalling ');
  },
  suv: true,
  luntai:[1,2,3,4]
};
  • In object ⾥ The function of is called ⽅ Law (methods)
  • Objects contain attributes and values , The value of an attribute can be of any type

Two 、js General operations in objects

    var car = {
      color: "red",
      height: 1.5,
      start: function () {
        console.log(" start-up ");
      },
      end: function () {
        console.log(" Stalling ");
      },
    };
    car.color = "blue"; // Change 
    car.suv = true; // increase 
    delete car.height; // Delete 
    console.log(car.color); // check 

You can also use square brackets [] To operate ( Not commonly used , More complicated )

    var car = {
      color: "red",
      height: 1.5,
      start: function () {
        console.log(" start-up ");
      },
      end: function () {
        console.log(" Stalling ");
      },
    };
    car["color"] = "blue"; // Change 
    car["suv"] = true; // increase 
    delete car["height"]; // Delete 
    console.log(car["color"]); // check 

3、 ... and 、 How to access its own attributes

        Can pass this Call its own properties and methods

    var car = {
      color: "red",
      height: 1.5,
      start: function () {
        console.log(" start-up ");
      },
      end: function () {
        console.log(" Stalling " + this.color);
      },
    };
    car.end();

Four 、 How to create objects

        1. Declare an object directly and assign values

    var car1 = new Object();
    car1.color = "red";
    car1.height = 1.9;
    console.log(car1);

        2. Custom constructors

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

原网站

版权声明
本文为[The secret of longevity is sleep]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207232107577847.html