简体   繁体   中英

Can a JavaScript function know its own name, including object it is contained within

I need a number of JavaScript functions to know their own names, including the object they are contained within. I can't seem to find a way to do this. All the examples on SO don't quite fit my use case. Here is a fiddle of what I'm looking for: http://jsfiddle.net/amczpro7/5/

window.myMainNameSpace = {};

myMainNameSpace.y = {
    z: function(funcToCall) {
        var x = eval("new " + funcToCall);
    }
}

myMainNameSpace.a = {
    b: function(args) {
        alert('I want to alert: myMainNameSpace.a.b');

        /*
        var myName = arguments.callee.toString();
        myName = myName.substr('function '.length);
        myName = myName.substr(0, myName.indexOf('('));
        alert(myName);

        console.log(arguments.callee);
        console.log(this.constructor);
        console.log(this.name);
        console.log(this);
        console.log(this.constructor.toString());
        */
    }
}

myMainNameSpace.y.z('myMainNameSpace.a.b({arg1:123})');

I would like to be able to make a function that would return myMainNameSpace.ab or myMainNameSpace.ab() so that I could place it in a handful of functions. Is this possible? Thanks!

You could do it without eval, you just have to iterate over each letter until aimSign is reached. In each iteration you put a new object within last nested object:

function callObjTail(obj){

  var lastObj;
  var lastSign;

  for(var i='a'.charCodeAt(); true; i++){
    console.log(i);

    if(obj[String.fromCharCode(i)]){
      lastObj = obj;
      lastSign = i;
      obj = obj[String.fromCharCode(i)];
    }
    else{
      break;
    }


  }

  if(lastObj){
    lastObj[String.fromCharCode(lastSign)]();
  }
  else{
    obj[Object.keys(obj)[0]]();
  }

}
function buildObj(aimSign){

  var obj = {};
  var head = obj;

  var nests = '';
  for(var i='a'.charCodeAt(); i < aimSign.charCodeAt(); i++){

    obj[String.fromCharCode(i)] = {};
    obj = obj[String.fromCharCode(i)];

  }

  return { head : head, tail: obj };

}

var obj = buildObj('e'); 
console.log(obj.head); // { a: { b: { c: { d: {}}}}

console.log(obj);


obj.tail.e = function(){ console.log('tail called');};
console.log(obj.head.a.b.c.d.e());
console.log(obj.tail.e());

// call tail at the end
callObjTail(obj.head);
callObjTail(obj.tail);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM