javascript - Can't call variable from another object -


i have 2 objects: myobject1 , myobject2. trying call private variable myobject1 using my0bject2 method called increment, console.log says nan. there way call myobject1 variable directly myobject2 method? maybe extend somehow?

var myobject1 = function() {    var x = 0;    return{} }();  var myobject2 = function() {    return{     increment: function() {         myobject1.x +=1;         console.log(myobject1.x);     }   } }();  myobject2.increment();  

when specify var x within myobject1 declaring variable private. thing has access variable methods within myobject1. noted, variable private.

you didn't make clear if wanted keep private or not assume want access it. couple of things here. attach variable object property of myobject1 via this. this refers current scope (myobject1) saying this.x within myobject1 saying myobject1.x. function, need return this instances of can access of public properties.

var myobject1 = function() {    this.x = 0;    return this;  }();    var myobject2 = function() {    return {      increment: function() {        myobject1.x +=1;        console.log(myobject1.x);      }    }  }();    myobject2.increment();

you return properties want, in case x. have more control on returned in case , same result above.

var myobject1 = function() {    var x = 0;    return {      x: x,      };  }();    var myobject2 = function() {    return {      increment: function() {        myobject1.x +=1;        console.log(myobject1.x);      }    }  }();    myobject2.increment();

either way, these methods both expose x property of myobject1 making public.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -