-1

The reason i am asking is because this code which has an array directly declared into the object will throw the following error: Uncaught ReferenceError: projects is not defined

var client = {
    projects: ['a', 'b', 'c', 'd'],
    test: function() {
        return projects.length;
    }
};
console.log(client.test());

Of course we can just declared the variable and then reference it within the object like this:

 var projects = ['a', 'b', 'c', 'd'];
    var client = {
        projects: projects,
        test: function() {
            return projects.length;
        }
    };
    console.log(client.test());

And that would work. But i really want to know why in the world is the first example giving the error. What is wrong with it??

escolta13
  • 49
  • 5
  • `return this.projects.length;` – n00dl3 Oct 06 '17 at 13:09
  • Because that's not how JS objects work? Some basic JS O.O tutorials will clear this up for you quickly. – Dave Newton Oct 06 '17 at 13:09
  • @DaveNewton Poor boy, give him some time to discover this. Then we could mark as duplicate his [next question](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback). – n00dl3 Oct 06 '17 at 13:16
  • @n00dl3 Fair enough—I’d already deleted my comment in preparation ;) – Dave Newton Oct 06 '17 at 13:23
  • 1
    @daveNewton i know we can use this to refer to the object. What is not obvious to me, (maybe to you it is cause you are such a genius) is why we have to use the this keyword, when on the first example, it is evident that projects has been defined as a variable (just like on the second example). I thought the question was a bit more profound than it seemed. – escolta13 Oct 06 '17 at 13:38
  • Ok, maybe my mistake is that i was assuming that key value pairs were variables when they are not. Are they? heheh. Sorry for my existencial JavaScript questions. – escolta13 Oct 06 '17 at 13:41
  • @escolta13 Me being a genius isn’t related-what I’m saying is that there are thorough tutorials that discuss JS’s OOP nature that will answer this question, and your next one, better than an answer on SO. Key/value pairs are just that-JS objects aren’t classes (which JS doesn’t have despite ES6’s syntactic sugar). – Dave Newton Oct 06 '17 at 13:52
  • All right, thanks @DaveNewton – escolta13 Oct 06 '17 at 13:59

1 Answers1

4

Use this.projects.length.

Within functions on the object, this refers to the current object.

Note that this will not work with arrow functions:

var client = {
    projects: ['a', 'b', 'c', 'd'],
    test: function() {
        return this.projects.length;
    }
};
console.log(client.test());

test: () => { would not work. However, with new object literal declaration syntax you could write test() { and that would work.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405