如何获取运行函数所属的对象名称?
我想在节点js中写一个数据库抽象,这里的情况是:
想象一下,我有一个对象的表数组,其中有一个数据库中的每个表的对象:
tables = [{ tableName: product, select: mySelect }, { tableName: order, select: mySelect }]
正如你可以看到每个表都有一个select。 现在的问题是,在mySelect函数,我想生成一个基于调用者的表名如下的SQL脚本:
function mySelect(){ var tableName = //Find the callers name (for instance product); var select = "SELECT * FROM " + tableName }
我怎样才能得到在JavaScript中调用select函数的对象的名称?
function myfunc() { alert(arguments.callee.name); } b = myfunc; b();
这会写“myfunc”(FF,Chrome,我觉得Safari)
如果你想从外面得到名字,你可以parsing出来:
b.toString();
但是我认为函数对象的name属性可能是你所需要的:
alert(b.name);
我已经读过,这是不可用的IE和Opera,所以你留下来在这些浏览器手动parsing出来。
Antoher的替代品
function antoherFunction(args) { var ret = args.toString(); ret = ret.substr('function '.length); ret = ret.substr(0, ret.indexOf('(')); return ret; }
但是..使用Function.caller是非标准的,并且arguments.callee在严格模式下是禁止的。
您始终可以将表名作为参数发送给函数。
例如
for(var i = 0, len = tables.length; i < len; i++) { tables[i].select(tables[i].tableName); }
或者如果你的对象像ORM(对象关系模型),每个表都有自己的类,那么你可以使用this.constructor或this.tableName作为你的对象已经包含表名。
例如
function mySelect(){ var tableName = this.constructor; // or tableName = this.tableName; var select = "SELECT * FROM " + tableName }
谢谢你们每一个实际上这篇文章帮助我。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
当我创build我的db.tables时使用绑定函数我将select函数绑定到当前表对象:
for(var i=0; i< tables.length; i++){ db.tables[tables[i].tablename] = {}; db.tables[tables[i].tablename].select = select.bind(tables[i]); }
这样我可以确保当我调用产品对象的selectfunction时,“this”关键字总是指“产品”对象。