Saya menulis ini:
//Make a copy of the old console.
var oldConsole = Object.assign({}, console);
//This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)
function setEnabled(bool) {
if (bool) {
//Rewrites the disable function with the original one.
console[this.name] = oldConsole[this.name];
//Make sure the setEnable will be callable from original one.
console[this.name].setEnabled = setEnabled;
} else {
//Rewrites the original.
var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};
//Defines the name, to remember.
Object.defineProperty(fn, "name", {value: this.name});
//replace the original with the empty one.
console[this.name] = fn;
//set the enable function
console[this.name].setEnabled = setEnabled
}
}
Sayangnya itu tidak berfungsi saat menggunakan mode ketat.
Jadi menggunakan console.fn.setEnabled = setEnabled
dan kemudian di console.fn.setEnabled(false)
mana fn
bisa hampir semua fungsi konsol. Untuk kasus Anda adalah:
console.log.setEnabled = setEnabled;
console.log.setEnabled(false);
Saya menulis ini juga:
var FLAGS = {};
FLAGS.DEBUG = true;
FLAGS.INFO = false;
FLAGS.LOG = false;
//Adding dir, table, or other would put the setEnabled on the respective console functions.
function makeThemSwitchable(opt) {
var keysArr = Object.keys(opt);
//its better use this type of for.
for (var x = 0; x < keysArr.length; x++) {
var key = keysArr[x];
var lowerKey = key.toLowerCase();
//Only if the key exists
if (console[lowerKey]) {
//define the function
console[lowerKey].setEnabled = setEnabled;
//Make it enabled/disabled by key.
console[lowerKey].setEnabled(opt[key]);
}
}
}
//Put the set enabled function on the original console using the defined flags and set them.
makeThemSwitchable(FLAGS);
demikian maka Anda hanya perlu memasukkan FLAGS
nilai default (sebelum menjalankan kode di atas), seperti FLAGS.LOG = false
dan fungsi log akan dinonaktifkan secara default, dan Anda masih bisa mengaktifkannya memanggilconsole.log.setEnabled(true)