const handlers = {
get: (target, key) => key in target ? target[key] : undefined,
set: (target, key, value) => {
if (key in target) {
target[key] = value;
}
return value;
}
};
const { revoke, proxy } = Proxy.revocable(ctx, handlers);
try {
proxy.canvas.width = 500;
} catch (e) { console.log("Access has been revoked", e); }
- , .
- .
, Proxy.revocable() , - , , , try/catch, , .
, , ( , - , ):
const RevocableAccess = (item, revoked = false) => ({
access: f => revoked ? undefined : f(item),
revoke: () => { revoked = true; }
});
const { revoke, access: useContext } = RevocableAccess(ctx);
useContext(ctx => ctx.canvas.width = 500);
revoke();
useContext(ctx => ctx.canvas.width = 200);
, -, , , . , .
-, , proxy.drawImage.apply(ctx, args) .
, , .
, , - Canvas, Image, Audio, Video, Promise (, ) .. Proxies, - , , , .
, :
const { proxy, revoke } = Proxy.revocable(ctx, {
get(object, key) {
if (!(key in object)) {
return undefined;
}
const value = object[key];
return typeof value === "function"
? (...args) => value.apply(object, args)
: value;
}
});
"" , .
, , , bind , this . JS.
... ; - , , , drawImage, :
const draw = proxy.drawImage;...
, , :
const ctx = proxy.canvas.getContext("2d");
... , .
, , , , DOM.