首页 > 解决方案 > 如何检查javascript中调用或未调用的对象属性或函数?

问题描述

我想检查我的对象属性和方法或其他任何东西是否被调用?例如,

// functions 

   function app(){
      return {
        name : 'Md Tahazzot',
        info : function(){
           return this.name;
        }   
      };
   }

现在,如果我将其称为 like app(),我的意思是在这种情况下,我不会被称为任何对象属性或方法。那么,是否可以检查一下我只被称为函数而不是这样app().name

标签: javascript

解决方案


你可以返回一个代理。如果曾经调用过代理的 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;


推荐阅读