Search code examples
javascriptprototypejavascript-objects

Having a problem about printing out object on console


I try to create a car object with the given values. While function is working, I print them on console and everything seems OK, however, when ı look the properties of car2 no values assigns it.My code is the following.

            function Car()
        {
            this.brand = "";
            this.wheel = 0;
            this.crash = false;
        }

  Car.prototype.createNewCar2 = function(array)
        {
            for(var i=0; i < array.length; i++)
                {
                    Object.keys(this)[i] = array[i];  
                    console.log(Object.keys(this)[i]);
                    console.log(array[i]);
                }
        }

        var car2 = new Car();
        car2.createNewCar2(["bmw",12,true]);
        console.log(car2);

When I create newcar I assign the values to the right index. I see it when I console.log them. However after creation, no values assigned to the car object. I couldn't figure out what is the problem. thanks in advance. My output is the following

brand
bmw
wheel
12
crash
true
Car {brand: "", wheel: 0, crash: false}

Solution

  • You are actually not assigning the value to the object's property using this. You are simply overwriting the key of the object. You need to assign the value of the object using this:

    var keys = Object.keys(this);
    this[keys[i]] = array[i];
    

    function Car() {
      this.brand = "";
      this.wheel = 0;
      this.crash = false;
    }
    
    Car.prototype.createNewCar2 = function(array) {
      var keys = Object.keys(this);
      for (var i = 0; i < array.length; i++) {
        this[keys[i]] = array[i];
        console.log(Object.keys(this)[i]);
        console.log(array[i]);
      }
    }
    
    var car2 = new Car();
    car2.createNewCar2(["bmw", 12, true]);
    console.log(car2);