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

Q1580 Can I create object getter and setter methods, as I can in Java?

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

Yes. The following defines a myObject obect constructor, with two publically accessible variables (there is currently no way to make them private), which also have corresponding getter and setter methods:

<script language="JavaScript"><!--
function g_valOne() { return this.iValueOne; }
function s_valOne(one) { this.iValueOne = one; }
function g_valTwo() { return this.iValueTwo; }
function s_valTwo(two) { this.iValueTwo = two; }

function myObject(one, two) {
    this.iValueOne = one;
    this.iValueTwo = two;

    this.getValueOne = g_valOne;
    this.setValueOne = s_valOne;
    this.getValueTwo = g_valTwo;
    this.setValueTwo = s_valTwo;
}

var object = new myObject(1,2);

document.write(object.getValueOne() + '<br>');
document.write(object.getValueTwo() + '<br>');

object.setValueOne(object.getValueOne() * 2);
object.setValueTwo(object.getValueTwo() * 2);

document.write(object.getValueOne() + '<br>');
document.write(object.getValueTwo() + '<br>');
//--></script>

©2018 Martin Webb