我是关于javascript的新手。所以我不知道我要找的是什么名字,我该怎么做?
在您阅读问题后,如果您的问题标题错误,您应该更改标题。
我正在使用console.log进行调试,但这会导致浏览器IE错误。我为这个问题做了以下功能。
var mylog=function(){
if (devmode && window.console){
console.log(arguments);
}
};
mylog("debugging");
现在我想使用所有控制台功能而没有错误,我可以这样做。
var myconsole={
log:function(){
if (devmode && window.console){
console.log(arguments);
}
}
,error:function(){
if (devmode && window.console){
console.error(arguments);
}
}
...
...
...
};
但我不想将所有控制台功能分别添加到myconsole对象。 我可以用PHP编写代码。
class MyConsole
{
function __call($func,$args)
{
if ($devmode && function_exists('Console')){
Console::$func($args); // Suppose that there is Console class.
}
}
}
MyConsole::warn("name",$name);
MyConsole::error("lastname",$lastname);
这可以使用__noSuchMethod__
方法,但这仅适用于firefox。
感谢您的帮助。
答案 0 :(得分:1)
不幸的是,你不能在JavaScript中这样做,语言不支持"没有这样的方法"概念
有两种选择:
使用字符串作为方法名称,例如:
function myconsole(method) {
var args;
if (devmode && window.console) {
args = Array.prototype.slice.apply(arguments, 1);
window.console[method].apply(window.console, args);
}
}
用法:
myconsole("log", "message");
myconsole("error", "errormessage");
myconsole
的肉在这里:
args = Array.prototype.slice.apply(arguments, 1);
window.console[method].apply(window.console, args);
第一行复制提供给myconsole
的所有参数,除了第一行(我们想要使用的方法的名称)。第二行从method
对象中的console
中检索由字符串命名的属性的函数对象,然后通过JavaScript apply
function调用它,为其提供这些参数。
第二种替代方案来自我,最好直接在代码中表达:
var myconsole = (function() {
var methods = "log debug info warn error assert clear dir dirxml trace group groupCollapsed groupEnd time timeEnd profile profileEnd count exception table".split(' '),
index,
myconsole = {},
realconsole = window.console;
for (index = 0; index < methods.length; ++index) {
proxy(methods[index]);
}
function proxy(method) {
if (!devmode || !realconsole || typeof realconsole[method] !== 'function') {
myconsole[method] = noop;
}
else {
myconsole[method] = function() {
return realconsole[method].apply(realconsole, arguments);
};
}
}
function noop() {
}
return myconsole;
})();
然后,您只需正常log
致电warn
,myconsole
等。