我正在使用原型在javascript中定义对象。
例如
Listerly.prototype.init = function() {
this.storage = new ListerlyStorage();
this.mainView = new ListerlyMainView();
}
一切正常,但我也尝试使用以下非常简单的日志记录方法来限制控制台日志记录:
Listerly.prototype.log = function(message) {
if (this.loggingEnabled) {
if (arguments && arguments.callee && arguments.callee.caller) {
var methodName = arguments.callee.caller.name;
console.log("Method name: "+ methodName);
if (this.logMethods["*"] || this.logMethods[methodName]) {
if (methodName) console.log(methodName + ":" + message);
else console.log(message);
}
} else {
console.log(message);
}
}
};
问题在于使用原型定义的函数没有函数名称,因此arguments.callee.caller.name
为空白。
有什么干净的方法可以设置函数名称?完成并.name
在每个函数上设置字段后,我尝试遍历原型,但这似乎不起作用。
有一个丑陋的解决方法,这样做会污染全局名称空间:
function listerly_finishedLoadingUser(user) {
this.user = user;
this.mainView.setUser(user);
}
Listerly.prototype.finishedLoadingUser = listerly_finishedLoadingUser;
希望有一种更清洁的方法吗?
Listerly.prototype.finishedLoadingUser =
function listerly_prototype_finishedLoadingUser (user) {
// …
};
您可以在函数内使用函数名进行严格模式下的递归,其中arguments.callee
严禁使用。
请注意,在较旧的(损坏的)JScript版本中,标识符也可以在函数外部使用,因此请明智地选择它。标识符长度也可能有(未指定)限制。
name
您使用的(只读)属性目前仅是事实上的标准。在不可用的地方,您可以从函数序列化中获得函数名称,即将Function
实例转换为字符串并提取标识符部分(就像我在JSX:object.js中所做的那样):
/**
* Returns the name of a function
*
* @param {Function|String} aFunction
* @return {string}
* The name of a function if it has one; the empty string otherwise.
*/
getFunctionName: function (aFunction) {
/* Return the empty string for null or undefined */
return (aFunction != null
&& typeof aFunction.name != "undefined" && aFunction.name)
|| (String(aFunction).match(/^\s*function\s+([A-Za-z_]\w*)/) || [, ""])[1];
},
通常,功能序列化是不可靠的。
还要注意,对象和实例的caller
属性是专有的。arguments
Function
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句