开发者

How to get data from a JavaScript Object Literal

开发者 https://www.devze.com 2023-04-12 12:12 出处:网络
I want to find a way to get the name \"objName\"开发者_开发百科 from the function \"fn\" defined inside the \"objName\".

I want to find a way to get the name "objName"开发者_开发百科 from the function "fn" defined inside the "objName".

See the comments to see how it should work.

this.objName = {
    fn : function () {console.log("????");}
}

this.objName.fn() // objName

Obviously, the "fn" function will not called in this way, but from a JavaScript Button action event. (the button is defined inside this.objName = { .... } )


Ugly but what about

this.ns = {};
this.ns.objName = {
    fn : function () {
        for (var k in ns)
            if (this === ns[k]) {
              alert(k);  
              return;
             }
     }
}

this.ns.objName.fn(); // objName

You could drop ns and use window.

Edit; after your update, if you want to access the object from within an event handler created by that object;

var Obj = new function() {
   this.objName = {
      id: 42,
      makeLink: function () {
         var self = this;
         document.getElementById("someelement").onclick = function(e) {
            alert(self.id); // 42
         };
      }
   }
}


I was looking for this before... until I realized (after looking here at stackoverflow) that if you are able to write:

this.objName.fn()

you already know what 'objName' is.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号