Wika
Wika

Reputation: 17

why alert not working in Javascript

i am designing a constructor function of an object type called Product that takes 3 parameters: aProdID, aDesc, and aPrice. displays the product object details by using alert(). For example, the output alert window should show the following if a product object is created with “A001”, “Coke”, “6” for the product number, product description, and product price respectively.

function product(aProdID, aDesc,aPrice){
     var quantity=0
     this.aProdID=aProdID;
     this.aDesc=aDesc;
     this.aPrice=aPrice;
     return aProdID, aDesc,aPrice;
}
var product1= new product('A001','Coke',6)

alert(product1);

But it display [Object Object] What's wrong with that? thanks a lot

Upvotes: 1

Views: 61

Answers (3)

Christos
Christos

Reputation: 53958

The product1 is an object. When you call the alert passing product1 as a parameter, the the toString method of the product1 is called. Since you haven't overriden this method, you see the default output, which it [Object object].

function Product(aProdID, aDesc, aPrice){
     this.aProdID=aProdID;
     this.aDesc=aDesc;
     this.aPrice=aPrice;
}

Product.prototype.toString = function(){
    return 'ProductId: ' + this.aProdID + 'Desc: ' + this.aDesc + 'Price: '+ this.aPrice;
}

var product1= new Product('A001','Coke',6)

alert(product1);

Side notes

As you will notice I renamed he constructor function from product to Product. This is a very common convention in the JavaScript language, in order to notify the reader of you code that this function is a constructor function (one that can be used along with the new operator to create other objects).

Furthermore, I removed the return statement, since a constructor function should not have a return statement. Last but not least I deleted the local variable called quantity, since its not used anywhere.

Below you will find two very helpful links regarding this context:

Upvotes: 3

Bc96
Bc96

Reputation: 13

Ohh same think happend to me then i found out that my information is be store in as object so in your case

alert(product1.aProdID);

To get the "A001"

Upvotes: 0

omar Samara
omar Samara

Reputation: 9

firstly you are using new to call the function and new always create object so the alert will be an object.

Upvotes: 0

Related Questions