Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How to associate functions with objects using JavaScript?
How to associate functions with objects using JavaScript?
✍: Guest
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>
This produces
title: Aliens director: Cameron
2011-08-09, 4385👍, 0💬
Popular Posts:
How To Enter Microseconds in SQL Statements? - MySQL FAQs - Introduction to SQL Date and Time Handli...
What are some uses of Intranets & Extranets? An "intranet" is the generic term for a collect...
How could Java classes direct program messages to the system console, but error messages, say to a f...
How To Check the Oracle TNS Settings? - Oracle DBA FAQ - ODBC Drivers, DSN Configuration and ASP Con...
How To Use "IF" Statements on Multiple Conditions? - Oracle DBA FAQ - Understanding PL/SQL Language ...