learningtech
learningtech

Reputation: 33683

how to access "this" object in javascript?

How come in the code below, the second line is giving me an undefined error?

function DAO()
{
        this.arrVariable = new Array();
        this.getItem = getItem;
        this.getItemQuery = getItemQuery;
}

function getItem(key)
{
        dao.arrVariable[key]();
}

function getItemQuery(key, url, options, pollfrequency)
{
        alert('hey');
}


var dao = new DAO();
dao.arrVariable['var1'] = function() { this.getItemQuery('a','b','c','d'); };

dao.arrVariable['var1']();

I want to be able to access the dao's getItemQuery as an object call. How do I do this?

Upvotes: 0

Views: 786

Answers (4)

Michael Berkowski
Michael Berkowski

Reputation: 270609

In that context, this refers to arrVariable. You can instead refer to it as dao.getItemQuery() inside the function:

dao.arrVariable['var1'] = function() { dao.getItemQuery('a','b','c','d'); };

Upvotes: 4

Ben L
Ben L

Reputation: 2561

THe this in function() { this.getItemQuery('a','b','c','d'); }; refers to function() not to DAO. You need to access DAO by:

dao.arrVariable['var1'] = function() { dao.getItemQuery('a','b','c','d'); };

Upvotes: 0

fuyou001
fuyou001

Reputation: 1642

dao.getItemQuery can access dao's property

Upvotes: 1

Kevin Ji
Kevin Ji

Reputation: 10489

You can use apply or call here.

So, instead of

dao.arrVariable['var1']();

Use either

dao.arrVariable['var1'].apply(dao, /* array of arguments here */);

or

dao.arrVariable['var1'].call(dao, /* arguments here, separated by commas */);

Upvotes: 1

Related Questions