Skip to content

装饰与转发 #314

@londbell

Description

@londbell

`let worker = {
someMethod() {
return 1;
},

slow(x) {
alert("Called with " + x);
return x * this.someMethod(); // (*)
}
};

function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) {
return cache.get(x);
}
let result = func.call(this, x); // "this" 现在被正确的传递了
cache.set(x, result);
return result;
};
}

worker.slow = cachingDecorator(worker.slow); // 现在让他缓存起来

alert( worker.slow(2) ); // 生效了
alert( worker.slow(2) ); // 生效了, 不会调用原始的函数了。被缓存起来了`
let result = func.call(this, x); 传递的this是window吗?

Metadata

Metadata

Assignees

No one assigned

    Labels

    SolvedProblem solved

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions