javascriptjavascript-objectsobjectname

How to find out javascript objects associated variable name


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?


Solution

  • 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