You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: questions/how-do-you-create-a-constructor-function/en-US.mdx
+23-6Lines changed: 23 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,13 +6,14 @@ title: How do you create a constructor function?
6
6
7
7
To create a constructor function in JavaScript, define a regular function with a capitalized name to indicate it's a constructor. Use the `this` keyword to set properties and methods. When creating an instance, use the `new` keyword.
8
8
9
-
```js
9
+
```js live
10
10
functionPerson(name, age) {
11
11
this.name= name;
12
12
this.age= age;
13
13
}
14
14
15
15
constjohn=newPerson('John', 30);
16
+
console.log(john.age); // 30
16
17
```
17
18
18
19
---
@@ -23,7 +24,7 @@ const john = new Person('John', 30);
23
24
24
25
A constructor function in JavaScript is a regular function that is used to create objects. By convention, the name of the constructor function starts with a capital letter to distinguish it from regular functions.
25
26
26
-
```js
27
+
```js live
27
28
functionPerson(name, age) {
28
29
this.name= name;
29
30
this.age= age;
@@ -34,7 +35,7 @@ function Person(name, age) {
34
35
35
36
Within the constructor function, the `this` keyword is used to refer to the object that will be created. Properties and methods can be assigned to `this`.
36
37
37
-
```js
38
+
```js live
38
39
functionPerson(name, age) {
39
40
this.name= name;
40
41
this.age= age;
@@ -50,7 +51,17 @@ function Person(name, age) {
50
51
51
52
To create an instance of the object, use the `new` keyword followed by the constructor function.
52
53
53
-
```js
54
+
```js live
55
+
functionPerson(name, age) {
56
+
this.name= name;
57
+
this.age= age;
58
+
this.greet=function () {
59
+
console.log(
60
+
`Hello, my name is ${this.name} and I am ${this.age} years old.`,
61
+
);
62
+
};
63
+
}
64
+
54
65
constjohn=newPerson('John', 30);
55
66
john.greet(); // Output: Hello, my name is John and I am 30 years old.
56
67
```
@@ -59,7 +70,7 @@ john.greet(); // Output: Hello, my name is John and I am 30 years old.
59
70
60
71
To save memory, it's a good practice to add methods to the constructor's prototype instead of defining them inside the constructor function.
61
72
62
-
```js
73
+
```js live
63
74
functionPerson(name, age) {
64
75
this.name= name;
65
76
this.age= age;
@@ -77,7 +88,13 @@ jane.greet(); // Output: Hello, my name is Jane and I am 25 years old.
77
88
78
89
You can check if an object is an instance of a constructor function using the `instanceof` operator.
0 commit comments