In our cat example, we've been able to instantiate our cat and provide a name separately. However, it may be desirable to require the cat to be named at instantiation so that we don't accidentally forget to name a cat. Constructors allow us to control instantiation.
By default, JS++ provides a constructor for you. This is known as the "default constructor." It is implicitly defined by JS++ if you do not have any constructors that you've explicitly defined. The default constructor takes no arguments and only returns a new instance of the class. To understand the default constructor, we can explicitly define it:
external $;
module Animals
{
class Cat
{
string _name;
var $element = $(
"""
<div class="animal">
<i class="icofont icofont-animal-cat"></i>
</div>
"""
);
Cat() {
}
property string name() {
return _name;
}
property void name(string name) {
_name = name;
}
void render() {
$element.attr("title", _name);
$("#content").append($element);
}
}
}
If you try to compile the project, there should be no problems. The reason is because we are instantiating the 'Cat' class without arguments in our main.jspp file. If you try to provide a few arguments, you will get a compile error for incorrect code.
As you can see from our explicitly-defined default constructor, the constructor has no parameters. Additionally, it doesn't do anything. (Constructors with no actions will still return a new instance of the class. Explicit 'return' statements inside constructors are unnecessary and not allowed because constructors always return a new instance of the class.)
One particular use for constructors is to initialize fields to custom values. Right now, if you instantiate the 'Cat' class, you will get the '_name' field as an empty string. If we want instances of 'Cat' to always have a name, we must require it during instantiation by specifying a constructor.
First, remove the getter and setter methods. Second, change the explicit constructor we defined to take one parameter: a 'string' for the cat's name. Finally, initialize the field to the argument provided to the constructor. (You should know how to do this by now.)
Your code in Cat.jspp should now look like this:
external $;
module Animals
{
class Cat
{
string _name;
var $element = $(
"""
<div class="animal">
<i class="icofont icofont-animal-cat"></i>
</div>
"""
);
Cat(string name) {
_name = name;
}
void render() {
$element.attr("title", _name);
$("#content").append($element);
}
}
}
Next, we have to change main.jspp:
import Animals;
Cat cat1 = new Cat("Kitty");
cat1.render();
Cat cat2 = new Cat("Kat");
cat2.render();
Compile the project. Open index.html in your web browser. You should see the two cats again. Hover over their images. You should once again see their names.
It's important to note that the implicitly-defined default constructor (that takes zero arguments) is no longer defined. Once you explicitly define a constructor for a class, the default constructor will not be explicitly defined. Thus, the only way to instantiate our 'Cat' class now is to use the constructor that requires a name. If you try to change the code in main.jspp to instantiate a class with zero arguments, you will get a compile error.
Similar Reads
JS++ Getters and Setters In our previous example, we defined a 'setName' method that sets a class 'name' field we declared. A method whose sole responsibility is to write to or modify a class field is known as a "setter" or "setter method." Conversely, a method whose sole responsibility is to return the current data of a cl
4 min read
JS++ | Types in JavaScript In this chapter, we're going to explore JavaScript programming styles and how developers worked with types in JavaScript (rather than JS++). This chapter will help you understand the next chapters which explain the JS++ type system in detail. In this tutorial, we will be using the Google Chrome web
10 min read
JS++ | Access Modifiers and 'super' Access modifiers allow us to change the "visibility" and "access privileges" of a class (or module) member. These are best understood by example. JS++ has three access modifiers: private, protected, and public. A private member is the least permissive. If a member is declared as 'private' it can onl
15 min read
JS++ | Static vs. Dynamic Polymorphism Static polymorphism is polymorphism that occurs at compile time, and dynamic polymorphism is polymorphism that occurs at runtime (during application execution). An aspect of static polymorphism is early binding. In early binding, the specific method to call is resolved at compile time. (JS++ also su
4 min read
JS++ | Classes, OOP, and User-defined Types Up until now, we've been declaring variables, looping over data, and writing 'if' and other conditional statements. These operations comprise the "imperative programming" paradigm where we describe "how" a program operates step by step (or, more specifically, statement by statement). Oftentimes, in
6 min read
JS++ | Modules Modules provide a way to organize code and divide an application into smaller parts. For example, a personal computer can be divided into keyboard, mouse, and monitor "modules" that can be separately connected. Ideally, in modular design, we want our modules to be independently "re-usable." A PS/2 k
4 min read
What is a Constructor in JavaScript? A constructor in JavaScript is a special function that is used to create and initialize objects. When we want to create multiple objects with similar properties and methods, the constructor is used as a blueprint to create similar objects. This is useful when you want to create multiple objects with
8 min read
How to create a JavaScript class in ES6 ? A class describes the contents of objects belonging to it: it describes a set of data fields (called instance variables) and it defines the operations on those fields (called methods). In order words, it is also defined as the collection or a group of object that contains object data types along wit
2 min read
Java Constructors In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Constructor and Method Declarations in class (ES2015+) In the ES2015+ version of JavaScript, a class is a blueprint for creating objects, and it provides a way to define the structure and behavior of those objects in a clear and organized way. A class is defined using the class keyword, and it has two main parts: the constructor and the methods. Constru
6 min read