Functions can use objects to remember the results of previous operations, making it possible to avoid unnecessary work. This optimization is called memoization.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var fibonacci = function(n) {
return n < 2 ? n : fibonacci(n-1) + fibonacci(n-2);
}
var fibonacci = function() {
var memo = [0, 1];
var fib = function(n) {
var result = memo[n];
if(typeof result !== 'number') {
result = fib(n-1) + fib(n-2);
memo[n] = result;
}
return result;
}
return fib;
}
继承三种方式
The instanceof operator tests presence of constructor.prototype in object’s prototype chain.
[Object] instanceof [Function]
伪类继承(Pseudoclassical)
1
2
3
4
5
6
functiona() {}
functionb() {}
b.prototype = Object.create(a.prototype);
b.prototype = new a();
b instanceof a; //true
原型继承(Prototypal)
1
2
3
4
5
6
7
8
9
var a = {
a1:2,
a2:3,
getA1() {returnthis.a1;}
}
var b = Object.create(a);
b.a1 = 4;
b.getA1();
函数继承(Functional)
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
functionsuperior(obj, name){
var superfunc = obj[name];
returnfunction() {
return superfunc.apply(obj, arguments);
}
}
var a = function(){
var private_a = 1;
var that = {};
var getPrivateA = function(){return private_a;}
that.getPrivateA = getPrivateA;
return that;
}
var b = function(){
var that = a();
var private_b = 4;
var getSuperiorA = superior(that, getPrivateA);
var getPrivateC = function() {
return that.getPrivateA() + private_b;
}
var getPrivateA = function() {
return that.getSuperiorA() + 'from parent';
}
that.getPrivateC = getPrivateC;
that.getPrivateA = getPrivateA;
return that;
}
Make Any Object reactable
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
var makeReactable = function(that){
var registry = {}
that.fire = function(event, parameters) {
var handlers,
params,
func,
type = typeof event === 'string' ?
event: event.type
if(registry.hasOwnProperty(type)){
handlers = registry[type];
handlers.forEach((handler) => {
params = handler.parameters;
func = handler.method;
if(parameters) {
params = params.concat(parameters);
}
if(typeof func === 'string'){
func = that[func];
}
func.apply(that, params)
})
}
returnthis;
}
that.on = function(type, method, parameters) {
var handler = {
method: method,
parameters: parameters || [],
}
if(registry.hasOwnProperty(type)){
registry[type].push(handler)
}else{
registry[type] = [handler];
}
returnthis;
}
}
var obj = {};
makeReactable(obj);
Object.defineProperty(obj, 'a', {
set: function(val){
if(val !== this.value){
this.fire('changed', [{param:'a', from: this.value, to: val}]);