Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f64c733

Browse files
prototypal inheritance
1 parent 6a3ce88 commit f64c733

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎06-code-reuse.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,53 @@ var inherit = (function(){
113113
}
114114
})();
115115
```
116+
117+
## klass
118+
119+
* some legacy JS libraries/frameworks emulate classes
120+
* usually there's a convention on how to name constructor functions (e.g. init)
121+
* they tend to support classical inheritance
122+
123+
## prototypal inheritance
124+
125+
* modern classless pattern
126+
* no classes, objects inherit from objects
127+
128+
```js
129+
function object (parent) {
130+
function F() {}
131+
F.prototype = parent;
132+
return new F();
133+
}
134+
135+
var parent = { ... }
136+
var child = object(parent);
137+
```
138+
139+
* children get parent methods and properties via ```__proto__``` link
140+
* parent can be created via constructor as well (not just literal)
141+
142+
## Object.create
143+
144+
* prototypal inheritance is built-in since ES5
145+
* ```Object.create(parentObject, ownPropertiesObject)```
146+
147+
## inheritance by copying properties
148+
149+
```js
150+
//shallow copy
151+
function extend (parent, child) {
152+
var key;
153+
child = child || {};
154+
for(key in parent){
155+
if(parent.hasOwnProperty(key)){
156+
child[key] = parent[key];
157+
}
158+
}
159+
return child;
160+
}
161+
```
162+
163+
* shallow copy just copies references of arrays and object
164+
* children can modify parent properties :(
165+
* deep copy is when array elements and object properties are copied as well

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /