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?

4

1 回答 1

1

我会稍微不同地处理它,您可以更直接地与 DOM/事件处理程序进行交互。这样做可以消除在对象范围之外公开函数名称的需要,因为 click 事件现在直接绑定到函数本身。

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
于 2014-09-16T08:44:50.543 回答