JavaScript의 noSuchMethod 기능을 사용하면 존재하지 않는 메서드에 대한 호출을 가로챌 수 있습니다. . 그러나 속성에 대한 유사한 메커니즘이 있습니까?
ES6 프록시는 속성 액세스를 사용자 정의하는 기능을 제공합니다. 이를 활용하여 속성에 대해 __noSuchMethod__와 유사한 동작을 에뮬레이트할 수 있습니다.
function enableNoSuchMethod(obj) {
return new Proxy(obj, {
get(target, p) {
if (p in target) {
return target[p];
} else if (typeof target.__noSuchMethod__ == "function") {
return function(...args) {
return target.__noSuchMethod__.call(target, p, args);
};
}
}
});
}
다음은 프록시를 사용하여 알 수 없는 속성을 처리할 수 있는 "Dummy" 클래스를 구현하는 예입니다.
function Dummy() {
this.ownProp1 = "value1";
return enableNoSuchMethod(this);
}
Dummy.prototype.test = function() {
console.log("Test called");
};
Dummy.prototype.__noSuchMethod__ = function(name, args) {
console.log(`No such method ${name} called with ${args}`);
};
var instance = new Dummy();
console.log(instance.ownProp1);
instance.test();
instance.someName(1, 2);
instance.xyz(3, 4);
instance.doesNotExist("a", "b");
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3