0
Can anybody help me here. Sub: object constructor in Javascript.
//questions are written in comment below this code. function Data(fn,ln,id,city) { this.FirstName=fn; this.LastName=ln;. this.Id=id;. this.City=city;. } var p1=new Data("john", "smith", 1,"Bangalore"); var p2=new Data("David", "williams", 2, "mumbai"); var p3=new Data("Emily","Adams",3, "Delhi"); document.write(p1.FirstName); docunent.write("<br>"); document.write(p2.City); alert("p3.city"); //Q1)here,what is (fn,ln,id,city)? //Q2)what is the difference between (FirstName,LastName,Id,City)and(fn,ln,id, city)? What if both are same? //Q3)What is "new Data" here in object create section?
2 odpowiedzi
+ 1
function Data is an object constructor function, this keyword refers to the object created, p1 is an example of an object created by the function.
Q1: fn, ln, id, city are parameters of the function, they will hold the values of the arguments you pass to them as in case of p1: john is represented by fn, smith is represented by ln and so on...they can be anything, they are like variables you declare and assign the value of arguments passed to the function to them.
Q2: FirstName, LastName, Id, City are properties of the object you create, they can be named anything, and they can have the same name as fn, ln, id, city (the parameters), you can set the properties of the object inside the function constructor or outside it.
Q3: You said it your self, it is an object created, and that's the role of new keyword, it is used to create a new object of the same type "Data".
+ 2
Thanks for your response.. Luckily understood this topic today after 2 days of struggle. However some sort of confusion was there.you make it clear.
Thank you very much👍☺️