```javascript function createIncrementor(start) { return function () { return start++; }; }
var inc = createIncrementor(5);
inc() // 5 inc() // 6 inc() // 7 ```
```java class Incrementor { private int start;
Incrementor(int start) { this.start = start; }
int inc() { start++; }
} ```
codehz
2021-01-08 18:01:55 +08:00
是这样的,你可以 function Class() { let x = 1; let y = 2; return function(action, params) { switch(action) { case "get-x": return x; break; case "set-x": x = params[0]; break; case "get-y": return y; break; case "set-y": y = params[0]; break; default: throw new Error("not implemented"); } } } 然后 let instance = Class() console.log(instance("get-x")); // 1 instance("set-x", [5]); console.log(instance("get-x")); // 5 顺带提示,这种方法还可以实现继承,多态等其他面向对象特性