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

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

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

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

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>

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.