Evan Bose
Evan Bose

Reputation: 11

I have a problem with 'with' keyword in Javascript when i run the program it showing undefined value what's the reason?

</HEAD>
<BODY>
    <script type = "text/javascript">
        function Car(amount,color){
            with(this){
                Carprice = amount
                CarColour = color
                
            }

        }
        var Nissan = new Car(10000,"red")
        document.write(Nissan.Carprice)
        document.write(Nissan.CarColour)

        
    </script>

</BODY>
</HTML>

I have created a constructor function with parameter amount and color but I'm getting an undefined value when i run this code i want the parameters to be printed

Upvotes: 1

Views: 28

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19654

Rather than using deprecated features, use class:

<script type = "text/javascript">
  class Car {
    constructor(amount, color) {
      this.Carprice = amount;
      this.CarColour = color;
    }
  }

  let Nissan = new Car(10000, "red");
  document.write(Nissan.Carprice);
  document.write(Nissan.CarColour);
</script>

Upvotes: 1

Related Questions