Object Constructors in JavaScript
Objects in JavaScript consist of key-value pairs contained within curly brackets {}. Here's an example:
myObject = { subject: "programming", language: "JavaScript", }
In this example, "subject and "language" are the keys, and "programming" and "JavaScript" are the values.
An object constructor is a special type of function in JavaScript that is used to create and initialize objects. Constructors us e the "new" keyword to create instances of a particular object. With constructors we can easily create multiple instances of the same type of object, all with their own unique properties and methods. Here's a function that can be used to create objects:
function Person(name, age) { this.name = name this.age = age this.sayHello = function () { console.log(`My name is ${this.name}, and my age is ${this.age}.`) } }
Below we use the "new" keyword to create some "Person" objects:
const person1 = new Person("Bill", 40) const person2 = new Person("Joe", 32) const person3 = new Person("Mary", 21)
We can call the "sayHello" function on each new "Person" object like so:
person1.sayHello() person2.sayHello() person3.sayHello() Console output: My name is Bill and my age is 40. My name is Joe and my age is 32. My name is Mary and my age is 21.
The "this" keyword always refers to an object. The object it refers to will vary depending on how and where "this" is being called. "this" is used in different ways in different areas: calling "this" by itself will refer to the global window object, calling "this" within an object method will return that object's properties, and calling "this" within a function will again refer to the general window object.
Calling "this" by itself:
console.log('this alone', this)
Calling "this" within an object method:
const person = { firstName: "John", lastName: "Doe", id: 3456, getThis: function() { return this } } console.log("this in object method", person.getThis())
Calling "this" in a function:
function test() { console.log("this in a function", this) } test()
"this" will now refer again to the general window object.
Using "this" in an event listener will refer to the DOM element that fires the event:
document.getElementById('testBtn').addEventListener('click', function () { console.log('this in an event', this) })
In this example, the event listener was added to a button element, and after clicking the button we get "this in an event" in the console.