Ask a Question    Search Answers  

Category
Computers >> Programming Concepts >> Java

Question
How to associate functions with objects using JavaScript?  (1 answers) Posted by: venkatreddy04   Ask a Friend

Answers
1.

Let's now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this.

<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
}
var narnia = new movie("Narni","Andrew Adamson");
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 parenthisis, 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) {
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>
    Answered by: nvreddy


    Add an Answer to this Question
    Add a New Question
    Notify updates to this question
    Mail to a Friend
Rate this answer:       Exact       Correct       somewhat correct       wrong       spam

User comments


  What is the difference between Message Driven Beans and Stateless Session beans?
  What happens if remove( ) is never invoked on a session bean?
  What are the special design care that must be taken when you work with local interfaces?
  What is the difference between HttpServlet and GenericServlet?
  What are the common mechanisms used for session tracking? ?
  Explain the life cycle methods of a Servlet. ?
  How does JSP handle run-time exceptions? ?
  How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
  Explain the life-cycle mehtods in JSP?
  What environment variables do I need to set on my machine in order to be able to run Java programs?
  Can a public class MyClass be defined in a source file named YourClass.java? ?
  What will be the default values of all the elements of an array defined as an instance variable?
  What is the difference between static and non-static variables?
  How does Java handle integer overflows and underflows?
Add New Question
Glossary
Add Glossary
 
Copyright © 2009-10 Krify Software Technologies Pvt Ltd. All rights reserved.