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 doPost and doGet methods?
  How are Servlets and JSP Pages related?
  Give the Details of XML files used in Validator Framework?
  What is ActionForm?
  What are the types of resultsets?
  What are the standard isolation levels defined by JDBC?
  How can I enable session tracking for JSP pages if the browser has disabled cookies?
  What's a better approach for enabling thread-safe servlets and JSPs? ?
  How do I use a scriptlet to initialize a newly instantiated bean? ?
  Is servlet is used to create a dynamic webpage or Static webpage or both?
  What is default capacity of connection pool objects in pool of app-server Weblogic and Tomcat webserver?
  Can we apply multiple inheritence in java?
  How to define an Abstract class?
  What is similarities/difference between an Abstract class and Interface?
Add New Question
Glossary
Add Glossary
 
Copyright © 2009-10 Krify Software Technologies Pvt Ltd. All rights reserved.