Monday, June 29, 2015

How to associate functions with objects using JavaScript?



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 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) {
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

No comments:

Post a Comment

What is restrict option in directive?

The restrict option in angular directive, is used to specify how a directive will be invoked in your angular app i.e. as an attribute, class...