在这段代码中,我创建了一个名为someFunction的函数.然后我修改了Function.prototype.apply并调用方法.因此,我正在运行我的拦截代码(显示警报),而不是我的功能代码正在工作.但是"呼叫"和"应用"都不会拦截直接方法调用.是否有可能拦截这个?
Function.prototype.call = function(){alert("call");};
Function.prototype.apply = function(){alert("apply");};
function someFunction(){}
window.onload = function(){
someFunction.call(this); //call alert is shown
someFunction.apply(this); //apply alert is shown
someFunction(); //how can I intercept this?
}
Run Code Online (Sandbox Code Playgroud) 我有一个类,我想应用代理,观察方法调用和构造函数调用:
Calculator.js
class Calc {
constructor(){}
add(a, b) {
return a+b;
}
minus(a, b) {
return a-b;
}
}
module.exports = Calc;
Run Code Online (Sandbox Code Playgroud)
index.js
const Calculator = require('./src/Calculator');
const CalculatorLogger = {
construct: function(target, args, newTarget) {
console.log('Object instantiated');
return new target(...args);
},
apply: function(target, thisArg, argumentsList) {
console.log('Method called');
}
}
const LoggedCalculator = new Proxy(Calculator, CalculatorLogger);
const calculator = new LoggedCalculator();
console.log(calculator.add(1,2));
Run Code Online (Sandbox Code Playgroud)
当调用它时,我希望输出为:
对象实例化
方法叫做
但是,apply没有被调用,我认为这是因为我将Proxy附加到Calculator类,而不是实例化的对象,所以不知道apply陷阱.
如何在方法调用和构造函数调用上构建一个包含所有代理的"观察"代理.
我有以下代码,其中我使用代理对象(代理)来尝试捕获方法调用和属性访问:
示例: https: //jsfiddle.net/r8j4fzxL/2/
(function() {
'use strict';
console.clear();
//some empty class where I want to trap methods props
class X {
//...
}
let proxy = {
get: function(target, prop, receiver) {
console.log('get called: ',
'target:', target,
'prop:', prop,
'receiver:', receiver
);
//this is OK, if we are called as a method.
//but it isn't when called as .prop - because, obviously, we return a function here.
return function(...args) {
console.log('wrapper args:', args);
return 42;
}
},
};
let …Run Code Online (Sandbox Code Playgroud)