Object in JavaScript

Object Literal

1
2
3
4
5
6
7
8
9
10
const circle = {
radius: 1,
position: {
x: 1,
y: 1,
},
draw: function () {
console.log("draw");
},
};

Factory Function

Just like factories producing products, the factory functions produce objects

1
2
3
4
5
6
7
8
9
10
function createCircle(radius) {
return {
radius,
draw() {
console.log("draw");
},
};
}

const circle = createCircle(1);

Constructor Function

this is a reference to the object that is executing the current function.

1
2
3
4
5
6
7
8
function Circle(radius) {
this.radius = radius;
this.draw = function () {
console.log("draw");
};
}

const circle = new Circle(1);

new do 3 things:

  1. crates a new empty object
  2. set this point to this new empty object
  3. return this from constructor function

Dynamic Nature of Objects

1
2
3
4
5
6
7
8
9
10
11
12
13
const circle = {
radius: 1,
};

circle.color = "yellow";
circle.draw = function () {
console.log("draw");
};

delete circle.radius;
delete circle.draw;

console.log(circle);

Constructor Property

Every object in JavaScript has a property called constructor which references the function that was used to construct or create that object.

1
2
3
4
5
const circle1 = createCircle(1);
const circle2 = new Circle(1);

circle1.constructor; // Object()
circle2.constructor; // Circle()

When we create a object using the object literal syntax, internally the js engine uses Object() as the constructor function.

There are many other built-in constructor in js:

1
2
3
4
new String();
new Boolean();
new Number();
new Function();
1
2
3
4
5
const number = 1;
number.constructor; // Number()

const isHandsome = true;
isHandsome.constructor; // Boolean()

Functions are Objects

1
2
3
4
5
6
7
8
9
10
function Circle(radius) {
this.radius = radius;
this.draw = function () {
console.log("draw");
};
}

Circle.name;
Circle.length;
Circle.constructor;

When we declare a function using the function syntax, internally js engine will use the Function() constructor to create a function-typed object.

So, we can create a function using a more complex way:

1
2
3
4
5
6
7
8
9
10
11
12
const Circle = new Function(
"radius",
`
this.radius = radius;
this.draw = function() {
console.log("draw");
};
`
);

// now Circle is a function and we can call it as normal Constructor
const circle = new Circle(1);

Some Useful Methods in Function Object

Circle.call() can call a function, the first arg is thisArg, next we add our arg explicitly.

1
2
3
4
5
6
7
function Circle(radius, color) {
this.radius = radius;
this.color = color;
this.draw = function () {
console.log("draw");
};
}

The two function call syntax below will end up with the same results:

1
2
const circle1 = Circle.call({}, 1, "red");
const circle2 = new Circle(1, "red");

So do these two:

1
2
3
4
const circle3 = Circle.call(window, 1, "red");
const circle4 = Circle(1, "red");

console.log(window.color, window.radius);

Because without new, this will reference the window object.

Another method of function object is apply(), same as call() with slightly difference:

1
Circle.call({}, [1, "red"]);

The argument of the function is passed as array, so if somewhere in my application, there is an array and i need to pass it to the function, I can use the call() method.

Enumerating Properties in an Object

Simplest way: for-in loop

if you want to use for-of loop, you need to work with Object.keys or Object.entries

Finally, to check if a member is in an object, use the in operator.

Cloning an Object

Old style

1
2
const another = {};
for (let key of circle) another[key] = circle[key];

Morden JS

1
const another = Object.assign({ color: "red" }, circle1, student1);

We can use Object.assign to clone an object or combine multi objects into a single object.

Best Approach

using the spread operator:

1
const another = { ...circle };

Garbage Collection

In low level languages such as C/C++, when creating an object, we need to allocate memory to it, and when we were done we need to deallocate memory.

We don’t need these in JavaScript.

Memory is automatically allocated to object when it’s created, and when we were done using, we don’t have to deallocate the memory because JavaScript has a garbage collector, the job of it is to find the variable or constant that are not longer to use and deallocate the memory.

Built-in Object

MDN is your best friend when working with these built-in object.

Math

MDN of Math is your best friend!

Some examples:

  • Math.random() returns a pseudo-random number between 0 and 1.
  • Math.round() round a number.
  • Math.max() returns the maximun number among all args.

String

MDN of String is your best friend!

Some examples:

1
const msg = "hi sichen";
  • msg.length
  • msg[0]
  • msg.includes('sichen')
  • msg.startsWith('hi')
  • msg.endsWith('chen')
  • msg.indexOf('sichen')
  • msg.replace('hi', 'hello')
  • msg.toUpperCase()
  • msg.toLowerCase()
  • msg.trim() gets rid of all the white space before and after our message.
  • msg.trimLeft()
  • msg.split(' ') splits a string with the given character, returned as array.

Note that JavaScript uses back slash (\) to escape.

Template Literal

Staring from ES6, back tick can be used to produce string, we can format the string the way you want it to look like:

1
2
3
4
5
6
const name = "sichen";

console.log(`Hi,
I am ${name}!
'Thanks'!
`);

So we don’t need \n to break a new line, and ', " don’t need to be escaped because this is a new representation of string.

Date

The constructor Date() has many versions:

1
2
3
const now = new Date();
const date1 = new Date("March 8 2020 04:05"); // construct from a string
const now = new Date(2020, 0, 1, 9); // note that month starts from 0, so 0 represents January

There are many format of date string, see ECMA Specification

All these date object has a bunch of get and set methods, explore it with the intellisense.

They also have some methods for converting them to a string, type to to explore it with the intellisense.