current position:Home>JavaScript object

JavaScript object

2022-04-29 09:42:02Lonely fighter

1. Build an empty similar Person.java class

//1. Build an empty similar Person.java  class 
let Person = function () {
    }

// Another way : function Person(){}
  
//2. Instantiate the class ( Create objects based on this class )
let p = new Person();


//3. You can dynamically add properties and methods to objects  (java You are not allowed to )
p.name=" Zhang San ";// to p Object addition name attribute 
p.age=18;

p.run=function () {
    // to p Object addition run Method 
   alert(this.name+":"+this.age);
}

//4. Call the object's run Method 
p.run();

2. Create a class with constructor

    //1. Define an object with a constructor 
    let Car = function (name,price) {
    
        this.name=name;
        this.price=price;
        this.cell = function () {
    
            alert(" My name is "+this.name+" The price is :"+this.price+" element !");
        }
    }
    
    // Another way of writing :
    /** function Car(name,person){ this.name=" bentley "; this.price=500; this.cell=function(){ console.log(this.name+":"+this.price); } } */
    //2. Instantiate objects ( Create objects based on this class )
    let c1 = new Car(" Wei to Es8",580000);
    c1.cell();// Call the object's cell Method 

3. Instantiate an empty object directly ( Create objects directly )

    let p1 = {
    };
    // Add properties and methods dynamically 
    p1.name=" Li Bai ";
    p1.age=18;
    p1.run = function () {
    
        alert(this.name+":"+this.age);
    }
    p1.run();

4. Directly instantiate objects with properties and methods ( Directly create objects with properties and methods )

// Instantiate an object with properties and methods 
    let p2 = {
    
        name:" Zhang San ",
        age:66,
        run:function () {
    
            alert(this.name+":"+this.age);
        }
    }
    p2.run();

copyright notice
author[Lonely fighter],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290746389040.html

Random recommended