Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1660 Is it possible to add a property or a method to pre-built objects, such as Image objects?

irt.org | Knowledge Base | JavaScript | Object | Q1660 [ previous next ]

Q1660 Is it possible to add a property or a method to pre-built objects, such as Image objects?

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>

Feedback on 'Q1660 Is it possible to add a property or a method to pre-built objects, such as Image objects?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.