skip to Main Content

Is there a way of adding an object without having to declare a const?

function Car (make, color) {
    this.make = make,
    this.color = color,  
    this.greet = function () {
        console.log(`The make is ${this.make} and color is ${this.color}`);
  };
}

const newObject = "Toyota"

const ford = new Car("Ford", "blue")
ford.greet();``

const vauxhall = new Car("Vauxhall", "green")
vauxhall.greet();

I thought I may be able to have:

const newObject = "Toyota"

Then add Toyota in place of ford or vauxhall.

2

Answers


  1. There are 4 ways of creating objects:

    //Object Literal
    let obj1 = {car: "Toyota"}
    
    //Using Object Inbuilt Method
    let obj2 = new Object();
    obj2.car = "Toyota";
    
    //Using Object.Create
    let obj3 = Object.create();
    obj3.car = "Toyota";
    
    //Using a Constructor
    function Car(name){
     this.car = name;
    }
    let obj4 = new Car("Toyota"); 
    

    There is NO 5th way – and I don’t think you can on the fly create any object you want. The best you close in is — Object Literal.

    Login or Signup to reply.
  2. You can create a Car class and define the setter method of "make" and "color".

    class Car {
            constructor(make, color) {
                this.make = make;
                this.color = color;
            }
        
            set setMake(new_make) {
                this.make = new_make;
            }
            set setColor(new_color){
                this.color = new_color;
            }
            greet() {
                console.log(`The make is ${this.make} and color is ${this.color}`);
            }
        }
    
        let carObj = new Car("Ford","blue);
        carObj.greet();
    
        output: The make is Ford and color is blue
        
        carObj.setMake("Vauxhall");
        carObj.setColor("green");
        carObj.greet();
        
        output: The make is Vauxhall and color is green
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search