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

Q204 How can I add a method to an object?

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

Q204 How can I add a method to an object?

There are two ways you add a method to an object (and it has to be an object), either by using prototype:

<script language="JavaScript"><!--

// define the myString object
function myString(value) {
    this.value = value;
}

// define the textfunc() method
function testfunc(value) {
    this.value = value;
}

// set the prototype
myString.prototype.testfunc = testfunc;

// create an instance of a myString object
var mytext = new myString('this is a test');

// alert the value propert of the mytext myString object
alert(mytext.value)

// use the myString testfunc() method
mytext.testfunc('teststring');

// alert the value propert of the mytext myString object
alert(mytext.value)

//--></script>

Or by adding a method to the object:

<script language="JavaScript"><!--

// define the myString object
function myString(value) {
    this.value = value;
    this.testfunc = testfunc;
}

// define the textfunc() method
function testfunc(value) {
    this.value = value;
}

// create an instance of a myString object
var mytext = new myString('this is a test');

// alert the value propert of the mytext myString object
alert(mytext.value)

// use the myString testfunc() method
mytext.testfunc('teststring');

// alert the value propert of the mytext myString object
alert(mytext.value)

//--></script>

Note that both approaches will not work on older browsers.

Feedback on 'Q204 How can I add a method to an object?'


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.