0

In the code below, I can't access this.children from init(). Why can't I access it? How can I change my code to be able to access it?

Important: this.camera has to be accessible from outside the object. init() has to be private.

Please try not to only give a solution, but more of an explanation. I want to understand what I do.

PROJECT.element = function () {

    this.children = [1,2,5,8];


    ///////////
    //PRIVATE FUNCTIONS

    //Initialisation of the object.
    var init = function () {

        this.children.push(9);
    }

    init();
};

To keep Andy happy:

PROJECT.element.prototype.constructor = PROJECT.element;
var thisAwesomeVariableWithGreatNameForAndy = new PROJECT.element();

(I am sure that there are question similar to this one already, and I did read a nice amount of them, but it's hard to use the search function on "scope" and "object", because there are -a lot- of question)

Jordumus
  • 2,763
  • 2
  • 21
  • 38
  • Hint: your question title is about JS objects, but your code doesn't contain one. – Andy Nov 13 '15 at 11:46
  • @Andy: Presumably `new PROJECT.element` is being called at some point, creating an object. – T.J. Crowder Nov 13 '15 at 11:49
  • 1
    You're far more trusting than me @T.J.Crowder. – Andy Nov 13 '15 at 11:50
  • 1
    @Andy there we go :) Hope this helps you sleep tonight! ;) (but you had a fair point) – Jordumus Nov 13 '15 at 11:52
  • 1
    `this` in JavaScript is really not that difficult. It is **always** what is left of the dot at **CALLTIME**!. To the left of `init()` is nothing, so `this` is nothing *(or window, or the global object)*. Try `var init = (function() { ... }).bind(this);` or `init.call(this);` – Anders Marzi Tornblad Nov 13 '15 at 11:55
  • @atornblad: *"It is always what is left of the dot at CALLTIME!"* No, not always, as your examples demonstrate. – T.J. Crowder Nov 13 '15 at 12:02
  • Well, internally it is still *(semi-)* correct, since `.bind`, `.call`, and `.apply` create closures, where the actual calling of the function is not obvious. But yeah, my comment seems to contradict itself. :) – Anders Marzi Tornblad Nov 13 '15 at 12:39

0 Answers0