Objects – Introduction

What are objects?

Objects are fundamental in JavaScript. The concept of objects is used in many other programming languages, known as object-oriented programming languages (OOP languages). Objects in OOP can be compared to objects in real life, in the broadest sense: a real life tangible object, a person, an event, a process, etc.

In OOP, an object can be understood as a way to describe an object through its properties. In JavaScript, an object is an unordered collection of properties that, for instance, describe a robotic arm with properties like reach, maximum load, degrees of freedom, model etc. A property can also be a function that the object can perform, like opening the gripper of the robotic arm or moving the gripper from one position to an other. A property being a function is called a method.

In JavaScript a property is an association between a name (or key) and a value. The value can be a primitive or again an object. If the value is a function, the property is called a method.


const name = {
  // properties:
  firstName: "John",
  lastName: "Doe",
  // method:  
  fullName: function() {
    return this.firstName+" "+this.lastName;
  }
}

console.log( name.fullName() ); // logs: "John Doe"

An example

Next a simple example of an object "pen" with properties and methods in JavaScript.


<canvas id="myCanvas" width="300" height="200" style="background:tan;"></canvas>
<script>
'use strict';
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");	

// Define object "pen":
const pen = {
  // properties:
  color: 'black',
  lineWidth: 1,
  beginX: 0,
  beginY: 0,
  endX: 100,
  endY: 100,
  // method:
  drawLine: function() {
    ctx.beginPath();
    ctx.lineWidth = this.lineWidth;
    ctx.strokeStyle = this.color;			
    ctx.moveTo(this.beginX,this.beginY);
    ctx.lineTo(this.endX,this.endY);
    ctx.stroke();		
  }
}

// Drawing a red line from (0,0) to (300,200):	
pen.color = 'red'; // change property "color" of object "pen".
pen.endX = 300; // change property "endX" of object "pen".
pen.endY = 200; // change property "endY" of object "pen".
pen.drawLine(); // invoke method "drawLine" of object "pen".  
</script>	

Result:

As extra features (not included in the code shown above) you can continue the line by clicking anywhere in the canvas, and select a color to change the line color after the line continues. You can also and start over with a clean sheet or without clearing the canvas. And if you want to save your artwork, you can right-click the canvas and choose "save image as...". View the source code of this document if you want to see how the extra features are programmed (it's not difficult!).