Object-oriented JavaScript
constructors and member access
In JavaScript, rather than defining a class to be instantiated by objects, one writes a constructor of the objects. Variables and functions defined within the constructor body become the new member data (properties) and member functions (methods) of the object (in addition to any inherited properties and methods).
In an object’s public code and constructor, the variable
this
is defined to refer to the object.
Members defined in the constructor but not qualified by
this
are private to the objects’
code, meaning there is no direct access to them from the outside.
To make a member of the object public, qualify it by
this
:
this.member_name
To access a public member of an object from code outside the
object’s code, one connects the object variable name with a dot
“.
” to the member name.
object_variable.member_name
The keyword new
indicates to JavaScript that
a function call is an object constructor, and creates a new object using
constructor supplied to it.
example: constructor, properties, creation and access
All JavaScript objects inherit from the the built-in type Object.
This type has one property: constructor
which is the object’s constructor function.
Any function in turn has a property prototype
.
One of the Object type methods is
toString()
,
which is called automatically to convert the object to a string.
We use these members in the code that is executed in the Inspect
button, and will discuss them more in the other pages.
Note that a member variable declared with the keyword
var
is accessible only within the code block
where it was declared, and so is called local. Without the
var
keyword, the variable could
accidentally refer to another variable defined outside the code block.
It is good practice in JavaScript (especially in object-oriented code) to
always declare variables using the
var
keyword
unless you really mean the variable to
be global (in which case, you should prefix its name with
global_
or
g_
to make this
obvious).
ownership of object members
A member of an object really belongs to its object: there is a distinct copy of the member for each object.
Note that the member prop2
of
tc
and tc2
vary
independently.
adding members on the fly
In JavaScript, after an object is created, public members may be added to
it at will, by simply assigning it a value.
Members can also be removed by operator delete
.
Clicking the first button gives tc2
a member
prop3
that tc
does not have. This is sometimes called dynamic polymorphism.
Programmers familiar with C, C++ and Java will find dynamic polymorphism very strange. It is not something special to JavaScript, however: it appears in Perl, Python and SmallTalk.
See
JavaScript Guide: Working with objects