0
what is object constructors in JavaScript?
I don't understand what is object constructors in JavaScript, can you explain me?
3 Réponses
+ 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"
0
Oh sorry, I neglected to notice that you said JavaSCRIPT. I will delete my previous comment😂😅
0
Thank you very much