Is the code correct | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Is the code correct

function contact(name, number) { this.name = name; this.number = number; } var a = new contact("David", 12345); var b = new contact("Amy", 987654321) a.print(); b.print(); Any time I try making print a function it gives an error saying that print isn't a function

27th Mar 2021, 10:33 PM
DURU SOMTOCHUKWU PHILIP
DURU SOMTOCHUKWU PHILIP - avatar
3 Answers
+ 4
DURU SOMTOCHUKWU PHILIP I agree with the answers Med Amine Fh and Luk gave above, but I thought I'd chip in with this. If you want to have a method called print, you can add it to the prototype of contact. Like this: function contact(name, number) { this.name = name; this.number = number; } contact.prototype.print = function() { console.log(`Name: ${this.name}; Number: ${this.number}`) } var a = new contact("David", 12345); var b = new contact("Amy", 987654321) a.print(); b.print();
27th Mar 2021, 11:45 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 3
The contact function (constructor) don't have print method . you just make 2 properties in that constractor (name, number). you can access both of them like this : for "a" instence : a.name a.number for "b" instence : b.name b.number
27th Mar 2021, 11:21 PM
Med Amine Fh
Med Amine Fh - avatar
+ 1
Try console.log(a).
27th Mar 2021, 10:44 PM
Luk
Luk - avatar