-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript-objects.html
214 lines (191 loc) · 32.4 KB
/
javascript-objects.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
<!DOCTYPE html><html lang="de-ch"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JavaScript objects - Finecloud</title><meta name="description" content="Object An object is a collection of properties A property has a name and a value An object can be seen as associative array (map) where the keys in the array are the names of the object’s properties // Create object as literal const bob…"><meta name="generator" content="Publii Open-Source CMS for Static Site"><link rel="stylesheet" href="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism-black.css"><link rel="canonical" href="https://www.finecloud.ch/javascript-objects.html"><link rel="alternate" type="application/atom+xml" href="https://www.finecloud.ch/feed.xml"><link rel="alternate" type="application/json" href="https://www.finecloud.ch/feed.json"><meta property="og:title" content="JavaScript objects"><meta property="og:site_name" content="Finecloud"><meta property="og:description" content="Object An object is a collection of properties A property has a name and a value An object can be seen as associative array (map) where the keys in the array are the names of the object’s properties // Create object as literal const bob…"><meta property="og:url" content="https://www.finecloud.ch/javascript-objects.html"><meta property="og:type" content="article"><link rel="shortcut icon" href="https://www.finecloud.ch/media/website/finecloud.png" type="image/png"><link rel="stylesheet" href="https://www.finecloud.ch/assets/css/style.css?v=39da73365516a098a9b73b721fc970e2"><script type="application/ld+json">{"@context":"http://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.finecloud.ch/javascript-objects.html"},"headline":"JavaScript objects","datePublished":"2023-01-17T20:13","dateModified":"2023-03-29T20:14","description":"Object An object is a collection of properties A property has a name and a value An object can be seen as associative array (map) where the keys in the array are the names of the object’s properties // Create object as literal const bob…","author":{"@type":"Person","name":"Finecloud","url":"https://www.finecloud.ch/authors/finecloud/"},"publisher":{"@type":"Organization","name":"Finecloud"}}</script><meta name="google-site-verification" content="seFY9U12uiEq5U3_MyZiX6XWzk0AVFl9zITr2ZKsytY"></head><body><div class="site-container"><header class="top" id="js-header"><a class="logo" href="https://www.finecloud.ch/">Finecloud</a><nav class="navbar js-navbar"><button class="navbar__toggle js-toggle" aria-label="Menu" aria-haspopup="true" aria-expanded="false"><span class="navbar__toggle-box"><span class="navbar__toggle-inner">Menu</span></span></button><ul class="navbar__menu"><li><a href="https://www.finecloud.ch/" target="_self">Blog</a></li><li><a href="https://www.finecloud.ch/tags/" target="_self">Tags</a></li></ul></nav><div class="search"><div class="search__overlay js-search-overlay"><div class="search__overlay-inner"><form action="https://www.finecloud.ch/search.html" class="search__form"><input class="search__input js-search-input" type="search" name="q" placeholder="search..." aria-label="search..." autofocus="autofocus"></form><button class="search__close js-search-close" aria-label="Close">Close</button></div></div><button class="search__btn js-search-btn" aria-label="Search"><svg role="presentation" focusable="false"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#search"/></svg></button></div></header><main><article class="post"><div class="hero"><figure class="hero__image hero__image--overlay"><img src="https://www.finecloud.ch/media/website/download.jpg" srcset="https://www.finecloud.ch/media/website/responsive/download-xs.jpg 300w, https://www.finecloud.ch/media/website/responsive/download-sm.jpg 480w, https://www.finecloud.ch/media/website/responsive/download-md.jpg 768w, https://www.finecloud.ch/media/website/responsive/download-lg.jpg 1024w, https://www.finecloud.ch/media/website/responsive/download-xl.jpg 1360w, https://www.finecloud.ch/media/website/responsive/download-2xl.jpg 1600w" sizes="100vw" loading="eager" alt=""></figure><header class="hero__content"><div class="wrapper"><div class="post__meta"><time datetime="2023-01-17T20:13">Januar 17, 2023</time></div><h1>JavaScript objects</h1></div></header></div><div class="wrapper post__entry"><div class="post__toc"><h3>Table of Contents</h3><ul><li><a href="#mcetoc_1gn0ic8ssj0">Object</a></li><li><a href="#mcetoc_1gn0ic8ssj1">Object Properties</a></li><li><a href="#mcetoc_1gna43tov6">Object Methods</a></li><li><a href="#mcetoc_1gna43tov7">Object Constructor</a></li><li><a href="#mcetoc_1gna43tov8">Altering Objects</a></li><li><a href="#mcetoc_1gnhh62kj1">The this-reference</a></li><li><a href="#mcetoc_1go1kjd5kjg">Prototype</a></li><li><a href="#mcetoc_1go1kjd5kjh">Inheritance</a><ul><li><a href="#mcetoc_1go1kjd5kji">Inheritance Helper Function</a></li></ul></li></ul></div><h2 id="mcetoc_1gn0ic8ssj0">Object</h2><ul><li>An object is a collection of properties</li><li>A property has a name and a value</li><li>An object can be seen as associative array (map) where the keys in the array are the names of the object’s properties</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-comment" style="color: grey;">// Create object as literal</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> bob = {
name: <span class="hljs-string" style="color: #6a8759;">"Bob"</span>,
age: <span class="hljs-number" style="color: #6897bb;">25</span>
};
<span class="hljs-comment" style="color: grey;">// Access properties</span>
<span class="hljs-built_in">console</span>.log(bob.name); <span class="hljs-comment" style="color: grey;">// >> Bob</span>
bob.age = bob.age+<span class="hljs-number" style="color: #6897bb;">1</span>;
bob.age++;
<span class="hljs-built_in">console</span>.log(bob.age); <span class="hljs-comment" style="color: grey;">// >> 27</span>
</pre><h2 id="mcetoc_1gn0ic8ssj1">Object Properties</h2><ul><li>Properties can dynamically be added to an object</li><li>Properties can be accessed using the dot or index operator</li><li>Property names that are not valid variable names have to be put in quotes</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">const</span> bob = {name: <span class="hljs-string" style="color: #6a8759;">"Bob"</span>, age: <span class="hljs-number" style="color: #6897bb;">25</span>};
<span class="hljs-comment" style="color: grey;">// Add new properties</span>
bob.hairColor = <span class="hljs-string" style="color: #6a8759;">"black"</span>;
<span class="hljs-built_in">console</span>.log(bob.hairColor); <span class="hljs-comment" style="color: grey;">// >> black</span>
<span class="hljs-built_in">console</span>.log(bob.lastname); <span class="hljs-comment" style="color: grey;">// >> undefined</span>
<span class="hljs-comment" style="color: grey;">// Access properties using the dot or index operator</span>
<span class="hljs-built_in">console</span>.log(bob.name); <span class="hljs-comment" style="color: grey;">// >> Bob</span>
<span class="hljs-built_in">console</span>.log(bob[<span class="hljs-string" style="color: #6a8759;">"name"</span>]); <span class="hljs-comment" style="color: grey;">// >> Bob</span>
<span class="hljs-comment" style="color: grey;">// Property with quoted name</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> alice = {
name: <span class="hljs-string" style="color: #6a8759;">"Alice"</span>,
<span class="hljs-string" style="color: #6a8759;">"year of birth"</span>: <span class="hljs-number" style="color: #6897bb;">1991</span>
};
<span class="hljs-built_in">console</span>.log(alice[<span class="hljs-string" style="color: #6a8759;">"year of birth"</span>]); <span class="hljs-comment" style="color: grey;">// >> 1991</span>
</pre><h2 id="mcetoc_1gna43tov6">Object Methods</h2><ul><li>An object property that points to a function value is called method</li><li>Within the method body, the this reference points to the object the method is called on</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">const</span> bob = {name: <span class="hljs-string" style="color: #6a8759;">"Bob"</span>};
<span class="hljs-comment" style="color: grey;">// Add method to object</span>
bob.speak = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>(<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" says: "</span>+phrase);
};
bob.speak(<span class="hljs-string" style="color: #6a8759;">"What's up?"</span>); <span class="hljs-comment" style="color: grey;">// >> Bob says: What's up?</span>
<span class="hljs-built_in">console</span>.log(bob.speak); <span class="hljs-comment" style="color: grey;">// >> [Function]</span>
<span class="hljs-comment" style="color: grey;">// Object literal with method</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> alice = {
name: <span class="hljs-string" style="color: #6a8759;">"Alice"</span>,
speak: <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>(<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" says: "</span>+phrase);
}
};
alice.speak(<span class="hljs-string" style="color: #6a8759;">"Great!"</span>); <span class="hljs-comment" style="color: grey;">// >> Alice says: Great!</span>
</pre><h2 id="mcetoc_1gna43tov7">Object Constructor</h2><ul><li>A constructor function is a normal function, but treated as constructor when called with the new operator</li><li>The this reference points to the new object</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-comment" style="color: grey;">// Constructor function</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Person</span>(<span class="hljs-params">name, age</span>) </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.name = name;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.age = age;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.speak = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>(<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" says: "</span>+phrase);
}
}
<span class="hljs-comment" style="color: grey;">// Create objects</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> alice = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Alice"</span>, <span class="hljs-number" style="color: #6897bb;">19</span>);
<span class="hljs-keyword" style="color: #cc7832;">const</span> bob = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Bob"</span>, <span class="hljs-number" style="color: #6897bb;">25</span>);
<span class="hljs-built_in">console</span>.log(alice.name); <span class="hljs-comment" style="color: grey;">// Alice</span>
bob.speak(<span class="hljs-string" style="color: #6a8759;">"I'm Bob"</span>); <span class="hljs-comment" style="color: grey;">// >> Bob says: I'm Bob</span>
</pre><h2 id="mcetoc_1gna43tov8">Altering Objects</h2><p>Objects can always be altered even if they were created using a constructor function:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Person</span>(<span class="hljs-params">name, age</span>) </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.name = name;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.age = age;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.speak = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> (<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name + <span class="hljs-string" style="color: #6a8759;">" says: "</span> + phrase);
}
<span class="hljs-keyword" style="color: #cc7832;">this</span>.sleep = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> () </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string" style="color: #6a8759;">"CHRRRZ Z Z z z..."</span>);
};
}
<span class="hljs-keyword" style="color: #cc7832;">const</span> bob = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Bob"</span>, <span class="hljs-number" style="color: #6897bb;">25</span>);
<span class="hljs-comment" style="color: grey;">// Alter bob</span>
bob.speak = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> () </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string" style="color: #6a8759;">"Sorry, I prefer writing"</span>);
}
bob.write = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> (<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name + <span class="hljs-string" style="color: #6a8759;">" writes: "</span> + phrase);
}
<span class="hljs-keyword" style="color: #cc7832;">delete</span> bob.sleep;
bob.speak(<span class="hljs-string" style="color: #6a8759;">"Bla bla"</span>); <span class="hljs-comment" style="color: grey;">// >> Sorry, I prefer writing</span>
bob.write(<span class="hljs-string" style="color: #6a8759;">"Bla bla"</span>); <span class="hljs-comment" style="color: grey;">// >> Bob writes: Bla bla</span>
bob.sleep(); <span class="hljs-comment" style="color: grey;">// ! TypeError: bob.sleep is not a function !</span>
<span class="hljs-comment" style="color: grey;">// bob is still a Person</span>
<span class="hljs-built_in">console</span>.log(bob <span class="hljs-keyword" style="color: #cc7832;">instanceof</span> Person); <span class="hljs-comment" style="color: grey;">// >> true</span></pre><h2 id="mcetoc_1gnhh62kj1">The this-reference</h2><ul><li>The this reference within a function points to the bound object</li><li>Functions are implicitly bound to the object the function is called on (methods)</li><li>Functions can be explicitly bound using bind or call</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-comment" style="color: grey;">// speak is not bound ('this' points to the global object or is undefined)</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">speak</span>(<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" says: "</span>+phrase);
}
speak(<span class="hljs-string" style="color: #6a8759;">"Hello"</span>); <span class="hljs-comment" style="color: grey;">// >> undefined says: Hello</span>
<span class="hljs-comment" style="color: grey;">// OR</span>
<span class="hljs-comment" style="color: grey;">// TypeError: Cannot read property name of undefined</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> alice = {name: <span class="hljs-string" style="color: #6a8759;">"Alice"</span>, speak: speak};
<span class="hljs-comment" style="color: grey;">// speak is implicitly bound to alice when called as method</span>
alice.speak(<span class="hljs-string" style="color: #6a8759;">"Hello"</span>); <span class="hljs-comment" style="color: grey;">// >> Alice says: Hello</span>
<span class="hljs-comment" style="color: grey;">// bind creates a new function which is explicitly bound to the passed object</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> aliceSpeak = speak.bind(alice);
aliceSpeak(<span class="hljs-string" style="color: #6a8759;">"Hello"</span>); <span class="hljs-comment" style="color: grey;">// >> Alice says: Hello</span>
<span class="hljs-comment" style="color: grey;">// call explicitly binds the function to the passed object and calls it</span>
speak.call(alice, <span class="hljs-string" style="color: #6a8759;">"Hi"</span>); <span class="hljs-comment" style="color: grey;">// >> Alice says: Hi</span>
</pre><h2 id="mcetoc_1go1kjd5kjg">Prototype</h2><ul><li>Most objects have a prototype, which is another object used as fallback source for properties</li><li>The prototype is often referenced by the __proto__ property (not standardized)</li><li>Each function has a prototype property which points to an object.</li><li>This object becomes the prototype of the objects created with the new operator from that function</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Person</span>(<span class="hljs-params">name, age</span>) </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.name = name;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.age = age;
}
<span class="hljs-comment" style="color: grey;">// Add functionality to Person's prototype</span>
Person.prototype.speak = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>(<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" says: "</span>+phrase);
};
<span class="hljs-keyword" style="color: #cc7832;">const</span> alice = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Alice"</span>, <span class="hljs-number" style="color: #6897bb;">19</span>);
<span class="hljs-keyword" style="color: #cc7832;">const</span> bob = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Bob"</span>, <span class="hljs-number" style="color: #6897bb;">25</span>);
<span class="hljs-comment" style="color: grey;">// alice and bob have the same prototype</span>
<span class="hljs-built_in">console</span>.log(alice.__proto__ === bob.__proto__); <span class="hljs-comment" style="color: grey;">// >> true</span>
<span class="hljs-comment" style="color: grey;">// New functionality can always be added to a prototype</span>
Person.prototype.sleep = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>() </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string" style="color: #6a8759;">"CHRRRZ Z Z z z ..."</span>);
};
bob.sleep(); <span class="hljs-comment" style="color: grey;">// >> CHRRR Z Z Z z z ...</span>
</pre><ul><li>Using prototype functions has the advantage that only one function instance is needed for all objects</li><li>But prototype functions have no access to local variables of the constructor function</li></ul><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Person</span>(<span class="hljs-params">name, age</span>) </span>{
<span class="hljs-comment" style="color: grey;">// Public property</span>
<span class="hljs-keyword" style="color: #cc7832;">this</span>.name = name;
<span class="hljs-comment" style="color: grey;">// Local variable (private property)</span>
<span class="hljs-keyword" style="color: #cc7832;">const</span> yearOfBirth = <span class="hljs-keyword" style="color: #cc7832;">new</span> <span class="hljs-built_in">Date</span>().getFullYear()-age;
<span class="hljs-comment" style="color: grey;">// Only functions defined in the constructor function can access local variables</span>
<span class="hljs-keyword" style="color: #cc7832;">this</span>.getYearOfBirth = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>() </span>{
<span class="hljs-keyword" style="color: #cc7832;">return</span> yearOfBirth;
}
}
Person.prototype.toString = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>() </span>{
<span class="hljs-comment" style="color: grey;">// Prototype functions have only access to the public properties of the object</span>
<span class="hljs-keyword" style="color: #cc7832;">return</span> <span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" was bron in "</span>+<span class="hljs-keyword" style="color: #cc7832;">this</span>.getYearOfBirth();
}
<span class="hljs-keyword" style="color: #cc7832;">const</span> bob = <span class="hljs-keyword" style="color: #cc7832;">new</span> Person(<span class="hljs-string" style="color: #6a8759;">"Bob"</span>, <span class="hljs-number" style="color: #6897bb;">25</span>);
<span class="hljs-built_in">console</span>.log(bob+<span class="hljs-string" style="color: #6a8759;">"!"</span>); <span class="hljs-comment" style="color: grey;">// >> Bob was born in 1996!</span>
</pre><h2 id="mcetoc_1go1kjd5kjh">Inheritance</h2><ul><li>Prototype properties are inherited over several levels</li><li>Inheritance is set up by<ul><li>calling the base constructor function to initialize the new object :</li></ul></li></ul><p><code>function Student(name, age, university) {</code><br><code>Person.call(this, name, age);</code><br><code>// ...</code><br><code>}</code></p><ul><li style="list-style-type: none;"><ul><li>setting the prototype object of the base constructor function as the prototype of the prototype object of the sub constructor function:</li></ul></li></ul><p><code>// Student’s prototype object must be replaced by a new object which</code><br><code>// has Person’s prototype object as prototype</code><br><code>Student.prototype = Object.create(Person.prototype);</code><br><code>Student.prototype.constructor = Student;</code></p><p>Example1:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Person</span>(<span class="hljs-params">name, age</span>) </span>{
<span class="hljs-keyword" style="color: #cc7832;">this</span>.name = name;
<span class="hljs-keyword" style="color: #cc7832;">this</span>.age = age;
}
Person.prototype.describe = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>() </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" is "</span>+<span class="hljs-keyword" style="color: #cc7832;">this</span>.age);
}
Person.prototype.speak = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>(<span class="hljs-params">phrase</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" says: "</span>+phrase);
}
<span class="hljs-comment" style="color: grey;">// Student extends Person</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Student</span>(<span class="hljs-params">name, age, university</span>) </span>{
Person.call(<span class="hljs-keyword" style="color: #cc7832;">this</span>, name, age);
<span class="hljs-keyword" style="color: #cc7832;">this</span>.university = university;
}
Student.prototype = <span class="hljs-built_in">Object</span>.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sleep = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>() </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string" style="color: #6a8759;">"CHRRRZ Z Z z z..."</span>);
}
Student.prototype.describe = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>()</span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" is a student at "</span>+<span class="hljs-keyword" style="color: #cc7832;">this</span>.university);
};
</pre><p>Example2:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-keyword" style="color: #cc7832;">const</span> bob = <span class="hljs-keyword" style="color: #cc7832;">new</span> Student(<span class="hljs-string" style="color: #6a8759;">"Bob"</span>, <span class="hljs-number" style="color: #6897bb;">25</span>, <span class="hljs-string" style="color: #6a8759;">"BFH"</span>);
<span class="hljs-built_in">console</span>.log(bob <span class="hljs-keyword" style="color: #cc7832;">instanceof</span> Student); <span class="hljs-comment" style="color: grey;">// >> true</span>
<span class="hljs-built_in">console</span>.log(bob <span class="hljs-keyword" style="color: #cc7832;">instanceof</span> Person); <span class="hljs-comment" style="color: grey;">// >> true</span>
bob.speak(<span class="hljs-string" style="color: #6a8759;">"Hi"</span>);
bob.describe();
bob.sleep();
<span class="hljs-comment" style="color: grey;">// >> Bob says: Hi</span>
<span class="hljs-comment" style="color: grey;">// >> Bob is a student at BFH</span>
<span class="hljs-comment" style="color: grey;">// >> CHRRRZ Z Z z z...</span></pre><h3 id="mcetoc_1go1kjd5kji">Inheritance Helper Function</h3><p>Using a helper function simplifies inheritance and makes it less error prone:</p><pre class="hljs" style="color: #a9b7c6; background: #282b2e; display: block; overflow-x: auto; padding: 0.5em;"><span class="hljs-comment" style="color: grey;">// Helper to correctly set up the prototype chain</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">extend</span>(<span class="hljs-params">base, sub</span>) </span>{
<span class="hljs-keyword" style="color: #cc7832;">const</span> origProto = sub.prototype;
sub.prototype = <span class="hljs-built_in">Object</span>.create(base.prototype);
<span class="hljs-keyword" style="color: #cc7832;">for</span> (<span class="hljs-keyword" style="color: #cc7832;">let</span> key <span class="hljs-keyword" style="color: #cc7832;">in</span> origProto) {
sub.prototype[key] = origProto[key];
}
<span class="hljs-built_in">Object</span>.defineProperty(sub.prototype, <span class="hljs-string" style="color: #6a8759;">'constructor'</span>, {
enumerable: <span class="hljs-literal" style="color: #6897bb;">false</span>,
value: sub
});
}
<span class="hljs-comment" style="color: grey;">//----------------------------------------</span>
<span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span> <span class="hljs-title" style="color: #ffc66d;">Prof</span>(<span class="hljs-params">name, age</span>) </span>{
Person.call(<span class="hljs-keyword" style="color: #cc7832;">this</span>, name, age);
}
Prof.prototype.describe = <span class="hljs-function"><span class="hljs-keyword" style="color: #cc7832;">function</span>() </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string" style="color: #6a8759;">"Prof. "</span>+<span class="hljs-keyword" style="color: #cc7832;">this</span>.name+<span class="hljs-string" style="color: #6a8759;">" is "</span>+<span class="hljs-keyword" style="color: #cc7832;">this</span>.age+<span class="hljs-string" style="color: #6a8759;">"years old"</span>);
}
extend(Person, Prof);
</pre></div><footer class="wrapper post__footer"><p class="post__last-updated">This article was updated on März 29, 2023</p><ul class="post__tag"><li><a href="https://www.finecloud.ch/tags/javascript/">javascript</a></li><li><a href="https://www.finecloud.ch/tags/softwareentwicklung/">software development</a></li></ul><div class="post__share"></div></footer></article><nav class="post__nav"><div class="post__nav-inner"><div class="post__nav-prev"><svg width="1.041em" height="0.416em" aria-hidden="true"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#arrow-prev"/></svg> <a href="https://www.finecloud.ch/difference-between-heap-and-stack.html" class="post__nav-link" rel="prev"><span>Previous</span> Difference between heap and stack</a></div><div class="post__nav-next"><a href="https://www.finecloud.ch/javascript-and-the-browser.html" class="post__nav-link" rel="next"><span>Next</span> JavaScript and the browser </a><svg width="1.041em" height="0.416em" aria-hidden="true"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#arrow-next"/></svg></div></div></nav><div class="post__related related"><div class="wrapper"><h2 class="h5 related__title">You should also read:</h2><article class="related__item"><div class="feed__meta"><time datetime="2023-04-10T08:46" class="feed__date">April 10, 2023</time></div><h3 class="h1"><a href="https://www.finecloud.ch/data-transfer-objects.html">Data Transfer Objects</a></h3></article><article class="related__item"><div class="feed__meta"><time datetime="2023-01-31T07:15" class="feed__date">Januar 31, 2023</time></div><h3 class="h1"><a href="https://www.finecloud.ch/javascript-advanced-features.html">JavaScript advanced features</a></h3></article><article class="related__item"><div class="feed__meta"><time datetime="2023-01-24T08:35" class="feed__date">Januar 24, 2023</time></div><h3 class="h1"><a href="https://www.finecloud.ch/javascript-and-the-browser.html">JavaScript and the browser</a></h3></article></div></div></main><footer class="footer"><div class="footer__copyright"><p>Powered by Publii</p></div><button onclick="backToTopFunction()" id="backToTop" class="footer__bttop" aria-label="Back to top" title="Back to top"><svg><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#toparrow"/></svg></button></footer></div><script>window.publiiThemeMenuConfig = {
mobileMenuMode: 'sidebar',
animationSpeed: 300,
submenuWidth: 'auto',
doubleClickTime: 500,
mobileMenuExpandableSubmenus: true,
relatedContainerForOverlayMenuSelector: '.top',
};</script><script defer="defer" src="https://www.finecloud.ch/assets/js/scripts.min.js?v=6ca8b60e6534a3888de1205e82df8528"></script><script>var images = document.querySelectorAll('img[loading]');
for (var i = 0; i < images.length; i++) {
if (images[i].complete) {
images[i].classList.add('is-loaded');
} else {
images[i].addEventListener('load', function () {
this.classList.add('is-loaded');
}, false);
}
}</script><script defer="defer" src="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism.js"></script></body></html>