0

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?

7
  • 2
    Why do you need to use "this"? My assumption is that getItemQuery actually does more than alert 'hey'? Perhaps you could elaborate? Commented Dec 6, 2011 at 2:03
  • The DAO object will have many more properties. I'd like to be access them when I'm in the function() {this.getItemQuery} Commented Dec 6, 2011 at 2:04
  • Refer to Michael's answer "this" is not needed for what you are doing. Commented Dec 6, 2011 at 2:05
  • Since dao.addVariable is declared as an array, do you really intend to add the object property var1 to it? In JavaScript, syntax like arrVariable['var1'] refers to an object property, not an array key. Commented Dec 6, 2011 at 2:07
  • Just as an aside, if you want an "associative array", i.e., you want to access elements based on key names rather than numeric indexes, then you should be using a JavaScript object: x = {}; x["key1"] = "A"; Commented Dec 6, 2011 at 2:07

4 Answers 4

4

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'); };
Sign up to request clarification or add additional context in comments.

1 Comment

To be exact, this refers to dao.arrVariable, not to the property var1 (which would be the function itself)
1

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 */);

Comments

1

dao.getItemQuery can access dao's property

Comments

0

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'); };

1 Comment

No, this refers to the object the function is called on. This might be the array in Johns secont-to-last line, or the window object if the function is called "directly".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.