0

I want to find out how to get variable name associated in object declaration. Easier to describe this problem is by an example, so:

function MyObject (){

    this.NeedToKnow = "";

    this.getLink = function() {
        html = '<a href="javascipt:' +this.NeedToKnow+'.doIt(passVal) ">M</a>';
        return html;
    }

    this.doIt = function(passVal) {
        //do stuff
    }
}

varNeedToKnow = new MyObject ();
var html = varNeedToKnow .getLink();

So my question is, how to find out "varNeedToKnow" to fill this.NeedToKnow inside object?

Is it even possible?

LuVe
  • 1
  • 2
  • possible duplicate of [How does "this" keyword work within a JavaScript object literal?](http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal) – Teemu Sep 16 '14 at 08:43
  • Then what if I change variable name and there is millions lines of code? – LuVe Sep 16 '14 at 08:43
  • bind functions to element instead of using inline js – Mithun Satheesh Sep 16 '14 at 08:44
  • @LuVe The accepted answer in the post linked in my comment above explains `this` quite well. – Teemu Sep 16 '14 at 08:46
  • @Teemu It is different problem, because THIS can access object it self, but not newly created object variable name. – LuVe Sep 16 '14 at 08:53
  • Actually it's not different. The second snippet in "As a function" case stands for constructors too, i.e. "`var that=this`". You're not supposed to use the name of the instance, use `this` to refer instance. – Teemu Sep 16 '14 at 10:38
  • My goal was to get associated variable name not function it self - just a name. :) – LuVe Sep 17 '14 at 06:24

1 Answers1

1

I would approach it slightly differently, whereby you interact more directly with the DOM/event handlers. Doing it this way removes the need to expose the names of functions outside the scope of your object, as the click event is now bound directly to the function itself.

function MyObject (){

    this.getLink = function() {
        var a = document.createElement('a');
        a.innerHTML = 'MyLink';

        if(a.addEventListener) {
            a.addEventListener('click', this.doStuff, false);
        } else {
            a.attachEvent('onclick', this.doStuff);
        }

        return a;
    };

    this.doStuff = function(passVal) {
        //do stuff
    };
}

var varNeedToKnow = new MyObject ();
var element = varNeedToKnow.getLink();
//element now contains an actual DOM element with a click event bound to your doStuff function
James Thorpe
  • 31,411
  • 5
  • 72
  • 93