检测何时从控制台调用函数的最佳方法 [英] Best way to detect when a function is called from the console

本文介绍了检测何时从控制台调用函数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道检测何时通过控制台直接调用方法或函数的最佳方法.据我目前所知,不可能在相同的函数调用上直接检测到它,但是使用函数的.call().apply()方法,我可以通过this对象传递其他数据.

I would like to know the best way to detect when a method or function is directly called through the console. As far as I currently understand, it's not possible to directly detect it on identical function calls, but using the .call() and .apply() methods of a function I can pass additional data through the this object.

给出以下代码结构:

(function(){
    var Player = {money: 0};
    window.giveMoney = function(amount){
        if (this.legit !== true)
            throw new Error("Don't try to cheat!");

        Player.money += amount;
    }
})();

我可以使用

window.giveMoney.call({legit: true}, 300);

在我的实际代码中告诉控制台直接调用和我自己的代码,但这显然不是万无一失的,因为也可以从控制台执行相同的代码以达到预期的效果.

in my actual code to tell a direct call from the console and my own code apart, but this is obviously not fool-proof, since the same code can also be executed from the console to achieve the desired effect.

我希望有一种方法可以从两个地方调用该函数,然后将调用的位置分开.如果没有办法,那么尝试阻止执行的最佳方法是什么?最好是根本不公开任何方法,并将所有内容保留在一个封闭的匿名函数中?

I would want a way to be able to call the function from both places and then tell the locations of the call apart. If there's no way to do that, what's the best way to try and prevent the execution anyway? Is it best to just not expose any methods at all, and keep everything inside a single closed-off anonymous function?

推荐答案

为防止全局访问,请确保您的代码处于关闭状态.如果要公开API,可以使用模块模式.

To prevent global access make sure your code is in a closure. If you want to expose an API you can do so using the module pattern.

(function() {
  var Game = {};
  Game.giveMoney = function(money) {
    console.log('Gave money (' + money + ')');
  };
})();

private 代码> IIFE (立即调用了 F 连接 E 表达)会将其锁定在一个闭合中.

Wrap all your private code in an IIFE (Immediately Invoked Function Expression) which will lock it up into a closure.

然后仅将自定义函数从闭包中暴露出来,以便您可以在控制台上使用它们(当然要在监督下).

Then expose only custom functions back out of the closure so you can use them on the console (with supervision of course).

window.Game = (function() {
  var player = {
    money: 500;
  };
  player.giveMoney = function(money) {
    console.log('Gave money (' + money + ')');
    player.money += money;
  };
  player.takeMoney = function(money) {
    console.log('Took money (' + money + ')');
    player.money -= money;
  };

  return {
    giveMoney: function(money) {
      console.error('Don\'t Cheat! A fine was charged.');
      player.takeMoney(Math.floor(player.money / 0.05));
    }
  };
})();

window.Game.giveMoney(200);

这篇关于检测何时从控制台调用函数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆