Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q204 How can I add a method to an object?

You are here: irt.org | FAQ | JavaScript | Object | Q204 [ previous next ]

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?'

©2018 Martin Webb