You are here: irt.org | FAQ | JavaScript | Object | Q1660 [ previous next ]
Yes. Try the following that adds properties and methods to individual object instances:
<script language="JavaScript"><!-- function myFunction() { alert(this.myProperty); } var myImage = new Image(); myImage.myProperty = 'Hello world'; myImage.myMethod = myFunction; myImage.myMethod(); //--></script>
I said individual object instances, as the following will fail with "myImage2.myMethod is not a function.":
<script language="JavaScript"><!-- function myFunction() { alert(this.myProperty); } var myImage = new Image(); myImage.myProperty = 'Hello world'; myImage.myMethod = myFunction; myImage.myMethod(); var myImage2 = new Image(); myImage2.myMethod(); //--></script>
To add a property or method to the Object type such that all instance of that object type inherit the property and/or method use the prototype keyword:
<script language="JavaScript"><!-- function myFunction2() { alert(this.myPrototypeProperty); } window.Image.prototype.myPrototypeMethod = myFunction2; window.Image.prototype.myPrototypeProperty = 'dlrow olleH'; var myImage3 = new Image(); myImage.myPrototypeMethod(); //--></script>