Object methods
In this chapter you will learn:
Using Functions as Methods
You can add functions to an object.
<!DOCTYPE HTML><!-- j a v a 2 s . c om-->
<html>
<body>
<script type="text/javascript">
var myData = {
name : "JavaScript",
weather : "Good",
printMessages : function() {
document.writeln("Hello " + this.name + ". ");
document.writeln("Today is " + this.weather + ".");
}
};
myData.printMessages();
</script>
</body>
</html>
Add methods after object creation
We can add new methods to an object by setting the value of a property to be a function.
<!DOCTYPE HTML><!-- java 2 s . co m-->
<html>
<body>
<script type="text/javascript">
var myData = {
name : "JavaScript",
weather : "Good",
};
myData.sayHello = function() {
document.writeln(this.name);
};
myData.sayHello();
</script>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
- How to access properties
- How use variable as the property name
- How to reference property name with space
- How to delete a property or method from an object
- How to determine if an object has a property
- How to enumerate object's properties
- How to pass in value with Object literals