作为一种学习体验,我正在尝试创建自己的面向对象的小控制台调试脚本.我希望它类似于jQuery,因为你可以将它称为函数(jQuery('div'))或对象(jQuery.ajax()).
我有下面的代码几乎正常工作.它基本上是"console.log"的别名.
我的目标是能够执行以下操作:
var log = new RadDebug;
// Create our function
log('You selected: %s', fruit_type);
// Invoke the top-level function
// Output: You selected: "Apple"
log.warn('You selected: %s', fruit_type);
// Invoke a method "warn", which displays a caution icon next to the log.
// Output: (!) You selected "Apple"
Run Code Online (Sandbox Code Playgroud)
我正在处理的脚本:
function RadDebug() {
var debug_enabled = (debug_mode && window.console && window.console.log instanceof Function);
// If this object was already initialize, redirect the function call to the ".log()" as default
if ( this.initialized ) {
return this.log.apply( this, arguments );
}
this.initialized = true;
this.log = function() {
if ( !debug_enabled ) return;
console.log.apply( console, arguments );
};
this.info = function() {
if ( !debug_enabled ) return;
console.info.apply( console, arguments );
};
// More methods below
}
Run Code Online (Sandbox Code Playgroud)
呼叫log.warn("hello world")按预期工作.
打电话log("hello world")告诉我TypeError: Object is not a function.
问题:如何使其作为一个函数工作并具有类似对象的属性?(就像jQuery一样)
(感谢@FelixKling已经解决了这个问题.如果要查看,最终的代码可以作为Gist获得).
不要使用RadDebug构造函数,只需将方法附加到函数本身.
例如:
var RadDebug = (function() {
// Some IIFE to keep debug_enabled and functions local
var debug_enabled = (debug_mode && window.console && window.console.log instanceof Function);
// Functions here
function log() {
if ( !debug_enabled ) return;
console.log.apply( console, arguments );
}
function info() {
if ( !debug_enabled ) return;
console.info.apply( console, arguments );
}
// ...
// Attach methods to "main" log function
log.log = log;
log.info = info;
// ...
// Return log function (RadDebug === log)
return log;
}());
Run Code Online (Sandbox Code Playgroud)
然后你用它作为
RadDebug('You selected: %s', fruit_type);
// same as
RadDebug.log('You selected: %s', fruit_type);
RadDebug.info('You selected: %s', fruit_type);
Run Code Online (Sandbox Code Playgroud)
或RadDebug任何你想要的别名(例如log).