-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path原生实现es6中的方法的原生实现.js
124 lines (83 loc) · 2.09 KB
/
原生实现es6中的方法的原生实现.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
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
<script>
// filter
Array.prototype.filter = function(result) {
var _array = [];
var _self = this;
for(var i = 0; i < _self.length; i++) {
if (result(_self[i])) {
_array.push(_self[i]);
}
}
return _array;
}
var newArray = [1, 2, 3, 4, 5].filter(function(i) {
return i != 1;
});
console.log(newArray);
// some
Array.prototype.some = function(result) {
var item;
var _self = this;
for(var i = 0; i < _self.length; i++) {
if (result(_self[i])) {
item = _self[i];
}
}
return item;
}
var newArray2 = [1, 2, 3, 4, 5].some(function(i) {
return i === 1;
});
console.log(newArray2);
// find
Array.prototype.find = function(result) {
var item;
var _self = this;
for(var i = 0; i < _self.length; i++) {
if (result(_self[i])) {
item = _self[i];
break;
}
}
return item;
}
var newArray3 = [1, 2, 3, 4, 5].find(function(i) {
return i >2;
});
console.log(newArray3);
// class原生实现
let Person = (function() {
const Person = function(name) {
if (typeof new.target === 'undefined') {
throw new Error('必须通过实例化调用');
}
this.name = name;
}
Object.defineProperty(Person.pertotype, 'sayName', function() {
value: function() {
if (typeof new.target !== 'undefined') {
throw new Error('必须不通过实例化调用');
}
console.log(this.name);
},
enumerable: false,
writable: true,
configgurable: true
});
return Person;
})();
let XMing = new Person('XMing');
XMing.sayName(); // XMing
// es6 class
let Person2 = class Person2 {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
let XHong = new Person2('XHong');
XHong.sayName(); // XHong
// new.target只有实例方法内使用 指向实例方法
<script/>