开发者

Java-script object - get variable name

To begin with, I'm not even sure, if it is the ri开发者_如何学Goght way to do it.

Let's say, i have script (jquery included) like this:

foo = function() {

    this.bar = function() {
    alert('I\'m bar');
    }

    this.test = function() {
    $('body').append('<a onclick="my_var.bar();">Click me</a>');
    }

this.test();

}

var my_var = new foo();

Is there any way, i could make variable "my_var" dynamic inside function "foo". So I could do something like

$('body').append('<a onclick="'+the_variable_which_im_assigned_to+'.bar();">Click me</a>');

Thank you

//Edit:

I'm sorry if i wasn't clear enough, because I'm not quite sure of what I'm trying to do myself.

My goal is to replace line

$('body').append('<a onclick="my_var.bar();">Click me</a>');

with

$('body').append('<a onclick="'+what_ever_should_go_here+'.bar();">Click me</a>');

So when i call

var my_var = new foo();
var your_var = new foo();
var our_var = new foo();

I would be able to call functions inside each object (after they append something into document body).


You should use anonymous handler functions instead of inline events, like this:

$('<a href="#">Click Me</a>')
    .click(function() { my_var.bar(); return false; })
    .appendTo('body');


In addition to switching from the inline event handler, you'll need to use a closure to access the Foo instance within the handler.

function Foo() {
    var self = this;
    this.test = function() {
        $('body').append(
            $('<button>something</button>').click(function () {
                self.bar(); return false;
        }));
    }
}


If that's the general plan you want/need to use to attach event handler, yeah, send in the name of the variable to the function that foo refers to:

foo = function(name_of_the_variable_which_im_assigned_to) { [...] };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜