1653635769
In this tutorial, you will learn about JavaScript constructor function with the help of examples.
In JavaScript, a constructor function is used to create objects. For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// create an object
const person = new Person();
In the above example, function Person()
is an object constructor function.
To create an object from a constructor function, we use the new
keyword.
Note: It is considered a good practice to capitalize the first letter of your constructor function.
In JavaScript, you can create multiple objects from a constructor function. For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23,
this.greet = function () {
console.log('hello');
}
}
// create objects
const person1 = new Person();
const person2 = new Person();
// access properties
console.log(person1.name); // John
console.log(person2.name); // John
In the above program, two objects are created using the same constructor function.
In JavaScript, when this
keyword is used in a constructor function, this
refers to the object when the object is created. For example,
// constructor function
function Person () {
this.name = 'John',
}
// create object
const person1 = new Person();
// access properties
console.log(person1.name); // John
Hence, when an object accesses the properties, it can directly access the property as person1.name
.
You can also create a constructor function with parameters. For example,
// constructor function
function Person (person_name, person_age, person_gender) {
// assigning parameter values to the calling object
this.name = person_name,
this.age = person_age,
this.gender = person_gender,
this.greet = function () {
return ('Hi' + ' ' + this.name);
}
}
// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');
// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
In the above example, we have passed arguments to the constructor function during the creation of the object.
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'male');
This allows each object to have different properties. As shown above,
console.log(person1.name);
gives John
console.log(person2.name);
gives Sam
// using object literal
let person = {
name: 'Sam'
}
// using constructor function
function Person () {
this.name = 'Sam'
}
let person1 = new Person();
let person2 = new Person();
// using constructor function
function Person () {
this.name = 'Sam'
}
let person1 = new Person();
let person2 = new Person();
// adding new property to person1
person1.age = 20;
Now this age
property is unique to person1
object and is not available to person2
object.
However, if an object is created with an object literal, and if a variable is defined with that object value, any changes in variable value will change the original object. For example,
// using object lateral
let person = {
name: 'Sam'
}
console.log(person.name); // Sam
let student = person;
// changes the property of an object
student.name = 'John';
// changes the origins object property
console.log(person.name); // John
When an object is created with an object literal, any object variable derived from that object will act as a clone of the original object. Hence, any change you make in one object will also reflect in the other object.
You can add properties or methods in an object like this:
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// creating objects
let person1 = new Person();
let person2 = new Person();
// adding property to person1 object
person1.gender = 'male';
// adding method to person1 object
person1.greet = function () {
console.log('hello');
}
person1.greet(); // hello
// Error code
// person2 doesn't have greet() method
person2.greet();
Output
hello
Uncaught TypeError: person2.greet is not a function
In the above example, a new property gender
and a new method greet()
is added to the person1
object.
However, this new property and method is only added to person1
. You cannot access gender
or greet()
from person2
. Hence the program gives error when we try to access person2.greet();
You can also add properties and methods to a constructor function using a prototype. For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// creating objects
let person1 = new Person();
let person2 = new Person();
// adding new property to constructor function
Person.prototype.gender = 'Male';
console.log(person1.gender); // Male
console.log(person2.gender); // Male
JavaScript also has built-in constructors. Some of them are:
let a = new Object(); // A new Object object
let b = new String(); // A new String object
let c = new Number(); // A new Number object
let d = new Boolean(); // A new Boolean object
In JavaScript, strings can be created as objects by:
const name = new String ('John');
console.log(name); // "John"
In JavaScript, numbers can be created as objects by:
const number = new Number (57);
console.log(number); // 57
In JavaScript, booleans can be created as objects by:
const count = new Boolean(true);
console.log(count); // true
Note: It is recommended to use primitive data types and create them in a normal way, such as const name = 'John';
, const number = 57;
and const count = true;
You should not declare strings, numbers, and boolean values as objects because they slow down the program.
#javascript #programming
1624392000
JavaScript Constructor Functions made simple.
📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=23AOrSN-wmI&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=10
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#javascript #functions #constructor #constructor functions #javascript constructor functions
1605017502
Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.
this.name = "Bob";const person = {
name: “Jon”,<span style="color: #008000">// Regular function</span> func1: <span style="color: #0000ff">function</span> () { console.log(<span style="color: #0000ff">this</span>); }, <span style="color: #008000">// Arrow function</span> func2: () => { console.log(<span style="color: #0000ff">this</span>); }
}
person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}person.func2(); // Call the Arrow function
// Output: {name:“Bob”}
const person = (name) => console.log("Your name is " + name); const bob = new person("Bob"); // Uncaught TypeError: person is not a constructor
#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions
1623309363
A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.
Private constructors in Java are accessed only from within the class. You cannot access a private constructor from any other class. If the object is yet not initialised, then you can write a public function to call the private instructor. If the object is already initialised, then you can only return the instance of that object. A private constructor in Java has the following use-cases:
The private constructor in Java is used to create a singleton class. A singleton class is a class in Java that limits the number of objects of the declared class to one. A private constructor in Java ensures that only one object is created at a time. It restricts the class instances within the declared class so that no class instance can be created outside the declared class. You can use the singleton class in networking and database connectivity concepts.
#full stack development #java #private constructor #private constructor java #private constructor in java: use cases explained with example #use cases explained with example
1601069940
Function Expression vs Function Declaration in JavaScript.
It was until during one of the JavaScript mock interviews did I came across the term function expression.
The question was: What is the difference between these two syntax?
function x(){
}
let x = function(){
}
I was clueless for a moment. After thinking a little, I could only come up with: the second syntax invokes an _anonymous _function and is assigned to a variable.
I was alien to the term hoisting.
In this article, we will acquaint ourselves with three simple terms: function declaration,_ function expression, _and hoisting.
What is function declaration?
Function declaration is also known as _function statement. _It contains the name of the function, parameters, and a return statement. **Naming the function **is what sets function declaration apart. Parameters and return statement is optional.
Function Declaration
What is function expression?
Function expression also has a name, parameters, and return statement. All of which are optional. The important thing to bear in mind is: the function here is _assigned _to a JavaScript variable.
Function Expression
#function-expression #function-declaration #functions-in-javascript #coding #javascript #express
1624410000
JavaScript factory functions made simple.
📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=jpegXpQpb3o&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=9
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#javascript #factory functions #functions #javascript factory functions