13
13
13
Home Interview Questions Certifications Aptitude Questions Tutorials Placement Papers Search
Resume Soft Skills Video Forum Blog
Google Search
Soft Skills
Communication Skills
Leadership Skills
.........More
How to associate
functions with
objects using
JavaScript?
}
}
var narnia = new
movie("Narni","Andrew
Adamson");
http://techpreparation.com/computer-interview-questions/javascript-interview-questions-answers13.htm#.U6gvy_mSwiQ
1/6
6/23/2014
Calling Web
Developers
modern.ie
1 Yr Online MBA
Rs.7500/Naukri.com Register Now
Jobs in TCS
Are You a Fresher?
Part Time Mba
Program
Speak English
Fluently
Upload Your CV For
Jobs
http://techpreparation.com/computer-interview-questions/javascript-interview-questions-answers13.htm#.U6gvy_mSwiQ
2/6
6/23/2014
document.write(narnia.toString());
</script>
This produces
title: Narni director: Andrew Adamson
Or we can use a previously defined function and assign it to a
variable. Note that the name of the function is not followed by
parenthesis, otherwise it would just execute the function and stuff
the returned value into the variable.
<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
http://techpreparation.com/computer-interview-questions/javascript-interview-questions-answers13.htm#.U6gvy_mSwiQ
3/6
6/23/2014
this.title = title;
this.director = director;
this.toString = movieToString; //assign function to this method
pointer
}
var aliens = new movie("Aliens","Cameron");
document.write(aliens.toString());
</script>
This produces
title: Aliens director: Cameron
eval()?
Objects have "prototypes" from which they may inherit fields and
functions.
<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director || "unknown"; //if null assign to
"unknown"
this.toString = movieToString; //assign function to this method
pointer
}
movie.prototype.isComedy = false; //add a field to the movie's
http://techpreparation.com/computer-interview-questions/javascript-interview-questions-answers13.htm#.U6gvy_mSwiQ
4/6
6/23/2014
prototype
var officeSpace = new movie("OfficeSpace");
var narnia = new movie("Narni","Andrew Adamson");
document.write(narnia.toString());
document.write("
Narnia a comedy? "+narnia.isComedy);
officeSpace.isComedy = true; //override the default just for this
object
document.write("
Office Space a comedy? "+officeSpace.isComedy);
</script>
unescape(), escape()
http://techpreparation.com/computer-interview-questions/javascript-interview-questions-answers13.htm#.U6gvy_mSwiQ
8
5/6
6/23/2014
10
11
12
13
35
http://techpreparation.com/computer-interview-questions/javascript-interview-questions-answers13.htm#.U6gvy_mSwiQ
6/6