Interviewer And Interviewee Guide

JavaScript Interview Question:

How to create an object using JavaScript?

Submitted by: Administrator
Objects can be created in many ways. One way is to create the object and add the fields directly.
<script type="text/javascript">
var myMovie = new Object();
myMovie.title = "Aliens";
myMovie.director = "James Cameron";
document.write("movie: title ""+myMovie.title+""");
<
This produces
movie: title "Aliens"
To create an object write a method with the name of object and invoke the method with "new".
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]

Use an abbreviated format for creating fields using a ":" to separate the name of the field from its value. This is equivalent to the above code using "this.".
<script type="text/javascript">
function movie(title, director) {
title : title;
director : director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]
Submitted by: Administrator

Read Online JavaScript Job Interview Questions And Answers
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.