0

what is object constructors in JavaScript?

I don't understand what is object constructors in JavaScript, can you explain me?

24th Aug 2019, 8:02 AM
Š”ŠµŃ€Š³ŠµŠ¹
Š”ŠµŃ€Š³ŠµŠ¹ - avatar
3 Answers
+ 4
They can make similar objects. There are three important words: "this", "new", and "prototype". So, the constructor function looks like this: function Person(name, age) { this.name = name; this.age = age; } Now, if you want to create instance objects, you have to do it like this: var person = new Person("David", 21); Notice the "new" keyword. You have to use that (to set the context of "this"), or else bad things happen. If you want to add methods, you can use the function's prototype: Person.prototype.inform = function() { console.log("My name is " + this.name + ", and I am " + this.age + " years old"); } So now, if you do: person.inform(); It will output: "My name is David and I am 21 years old"
24th Aug 2019, 8:43 AM
Airree
Airree - avatar
0
Oh sorry, I neglected to notice that you said JavaSCRIPT. I will delete my previous commentšŸ˜‚šŸ˜…
24th Aug 2019, 8:34 AM
Trigger
Trigger - avatar
0
Thank you very much
24th Aug 2019, 8:53 AM
Š”ŠµŃ€Š³ŠµŠ¹
Š”ŠµŃ€Š³ŠµŠ¹ - avatar