javascript - 如何检查javascript中调用或未调用的对象属性或函数?
问题描述
我想检查我的对象属性和方法或其他任何东西是否被调用?例如,
// functions
function app(){
return {
name : 'Md Tahazzot',
info : function(){
return this.name;
}
};
}
现在,如果我将其称为 like app()
,我的意思是在这种情况下,我不会被称为任何对象属性或方法。那么,是否可以检查一下我只被称为函数而不是这样app().name
?
解决方案
你可以返回一个代理。如果曾经调用过代理的 getter(或 setter?),那么您就知道除了简单地调用函数之外还做了一些事情——试图在返回的对象上获取或设置属性:
function app() {
const target = {
name: 'Md Tahazzot',
info: function() {
return this.name;
}
};
return new Proxy(target, {
get(target, prop) {
console.log('Get attempted');
return target[prop];
},
set(target, prop, newVal) {
console.log('Set attempted');
return target[prop] = newVal;
}
});
}
console.log('Creating "a":');
const a = app();
console.log('Creating "b":');
const b = app();
b.name;
console.log('Creating "c":');
const c = app();
c.foo = 'foo';
console.log(c.foo);
如果您必须从 外部执行此操作app
,则在返回对象后应用相同的逻辑:
function app() {
return {
name: 'Md Tahazzot',
info: function() {
return this.name;
}
};
}
const obj = new Proxy(app, {
get(target, prop) {
console.log('Get attempted');
return target[prop];
},
set(target, prop, newVal) {
console.log('Set attempted');
return target[prop] = newVal;
}
});
console.log('Proxy created');
obj.name;
推荐阅读
- multiprocessing - 如何使用 PyTorch 在 gpu 中运行特定代码?
- javascript - 如何在 react-native 中连接特殊符号,如 ¥
- c - mapPut 有什么问题?我找不到问题
- xss - 如何使用 HSTS(HTTP Strict Transport Security)拦截网站
- python - 使用 PyTorch 的 AlexNet 在训练后显示低准确率
- javascript - 验证输入字段 Fullname(Firstname,Lastname) - JavaScript
- github - Conda 构建:github 和 bitbucket
- python - 在 Python 3.5 中 Unpickling StandardScaler(从 Python 2.7 转储)
- c# - 如何从 EWS 交换服务器访问特定电子邮件
- javascript - 如何使用 {} 在 var 中包含 var