forked from lfthwjx/effective-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.js
36 lines (26 loc) · 850 Bytes
/
demo.js
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
// 尝试继承标准类
function Dir(path, entries) {
this.path = path;
for(var i = 0; i < entries.length; i++) {
this[i] = entries[i];
}
}
Dir.prototype = Object.create(Array.prototype);
var dir = new Dir('/temp/mysite', ['index.html', 'script.js', 'style.css']);
// dir的长度是0 继承没有成功
console.log(dir.length); // 0
// 查看对象属性
console.log(Object.prototype.toString.call(dir)); // [object Object]
console.log(Object.prototype.toString.call([])); // [object Array]
// 重新实现一个
function Dir1(path, entries) {
this.path = path;
this.entries = entries;
}
// 将相应的数组的方法委托给entries属性来完成
Dir1.prototype.forEach = function(f, thisArg) {
if(typeof thisArg === 'undefined') {
thisArg = this;
}
this.entries.forEach(f, thisArg);
};