我想知道检测何时通过控制台直接调用方法或函数的最佳方法。据我目前了解,不可能在相同的函数调用上直接检测到它,但是使用函数的 .call()
和 .apply()
方法我可以通过 this
对象传递额外的数据。
给定以下代码结构:
(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);
在我的实际代码中,将直接从控制台调用和我自己的代码区分开来,但这显然不是万无一失的,因为同样的代码也可以从控制台执行以达到预期的效果。
我希望有一种方法能够从两个地方调用函数,然后区分调用的位置。如果没有办法做到这一点,尝试阻止执行的最佳方法是什么?是否最好根本不公开任何方法,并将所有内容保存在一个封闭的匿名函数中?
最佳答案
要防止全局访问,请确保您的代码处于闭包中。如果你想公开一个 API,你可以使用 module pattern 来实现。 .
关闭
(function() {
var Game = {};
Game.giveMoney = function(money) {
console.log('Gave money (' + money + ')');
};
})();
将您所有的私有(private) 代码包装在IIFE 中(我立即我调用了F功能Expression)这将锁定它进入闭包。
模块
然后仅将自定义函数从闭包中公开出来,以便您可以在控制台上使用它们(当然要在监督下)。
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);
关于javascript - 检测何时从控制台调用函数的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000460/