• An interesting turn takes this code - which - in a nutshell:

    • defines the same structure but with use of constructor and prototype
    • creates first an obj with id = "objx"
    • creates second an object with id = "obj"
    • invokes .meth() on obj

      // .bind() not working?
      
       
      function Obj(id) {
      this.id = id;
      this.cnt = 0;
      }
      Obj.prototype.meth = function() {
      console.log("-----.meth()-----");
      console.log(this);
      console.log("id=" + this.id);
      if ("obj" == this.id) {
        console.log("'this' is 'obj':"); 
        console.log("id="+ this.id + " in invocation # " + (++this.cnt));
        if (this.cnt < 3) { var _t = this; setTimeout(_t.meth,1); }
      } else {
        console.log("'this' is (unexpectedly) NOT 'obj'"); 
      }
      console.log("-----/.meth()-----");
      }; 
      
      
      var objx = new Obj("objx");
      
      var obj = new Obj("obj");
      
      obj.meth.bind(obj);
      
      function onInit() {
      obj.meth();
      }
      

    The output for the bound this produced with console.log(this) must have somthing to do with the constructor, becauase all - both - instances objx and obj are listed:

             |_| http://espruino.com
     1v81 Copyright 2015 G.Williams
    >echo(0);
    =undefined
    >onInit();
    -----.meth()-----
    {
      "id": "obj",
      "cnt": 0 }
    id=obj
    'this' is 'obj':
    id=obj in invocation # 1
    -----/.meth()-----
    =undefined
    -----.meth()-----
    {
      "Obj": function (id) {
      this.id = id;
      this.cnt = 0;
    },
      "objx": {
        "id": "objx",
        "cnt": 0 },
      "obj": {
        "id": "obj",
        "cnt": 1 },
      "onInit": function () {
      obj.meth();
    },
      "console": function () { [native code] }
     }
    id=undefined
    'this' is (unexpectedly) NOT 'obj'
    -----/.meth()-----
    > 
    
About

Avatar for allObjects @allObjects started