Calling a JavaScript variable inside a function from outside - javascript

var func = function(){
this.innerVar = 'hello';
}
console.log(func.innerVar); // it prints undefined
can I access the variable innerVar from outside?

var func = function(){
this.innerVar = 'hello';
}
Now you have these options:
1) Using func as a constructor:
console.log(new func().innerVar);
2) Using the apply method on the function:
var obj = {};
func.apply(obj);
console.log(obj.innerVar);
3) Using the call method on the function (cheers to #dev-null):
var obj = {};
func.call(obj);
console.log(obj.innerVar);
4) Using the bind method on the function:
var obj = {};
func.bind(obj)();
console.log(obj.innerVar);
5) And the crazy stuff:
console.log(func.apply(func) || func.innerVar);

That's basic
var func = function(){
this.innerVar = 'hello';
}
console.log((new func()).innerVar);
Create a object new func().
Set its property innerVar this.innerVar = 'hello';.
Fetch its property (new func()).innerVar

var Func = function(){
this.innerVar = 'hello';
}
var func = new Func; // Creates an instance of your Func class
console.log(func.innerVar);

var func = function() {
func.innerVar = 'hello';
};
func.innerVar; // undefined
func();
func.innerVar; // ‘hello'

Related

How can I reference the parent object in a child function?

Given an object like this:
var MyObj = {
bar: 10,
foo: function() {
alert(MyObj.bar);
}
}
How can I generically reference MyObj from MyObj.foo such that if I were to change var MyObj to var MyObj2 I wouldn't need to modify the foo function?
If you want to treat MyObj like a class, you could do something like what lumio suggested, or you could do something like
function MyObj(){
this.bar = 10;
this.foo = function(){
return this.bar;
}
}
var a = new MyObj();
var b = new MyObj();
b.bar = 5;
console.log(a.foo(), b.foo()) // 10 5
If instead, you just want to reference the object's bar value, then you could just replace the alert(MyObj.bar); with alert(this.bar);
Classes would help you a lot here. In ES5 classes can be created like so:
function MyObj() {
this.bar = 10;
}
MyObj.prototype.foo = function() {
console.log( this.bar );
}
var objInstance = new MyObj;
objInstance.foo();
var objInstance2 = new MyObj;
objInstance2.bar = 20;
objInstance2.foo();
ES6 allows an even better notation:
class MyObj {
constructor() {
this.bar = 10;
}
foo() {
console.log( this.bar );
}
}
var objInstance = new MyObj;
objInstance.foo();
var objInstance2 = new MyObj;
objInstance2.bar = 20;
objInstance2.foo();
Use babel to convert it to ES5.

How can I make privileged JS methods?

I want to be able to call sub-functions that work with private data. Currently I have this:
var myFunction4 = function() {
this.secret1 = 0;
this.secret2 = 0;
var that = this;
this.iterate1 = function(){
return that.secret1++;
}
this.iterate2 = function(){
return that.secret2++;
}
this.addSecrets = function(){
return that.secret1 + that.secret2;
}
return {
iterate1: this.iterate1,
iterate2: this.iterate2,
addSecrets: this.addSecrets,
}
};
The bad thing about this is that to call one of the methods, I have to do:
myFunction4().iterate1();
Which executes myFunction4() every single time I want to access a method. Not only is this inefficient, but it resets secret1 each time so I can't iterate it. I've tried using the new operator, but that exposes secret1 and secret2, and it messes up the ability to nest functions deeply.
var myFunction3 = function() {
this.secret1 = 0;
this.secret2 = 0;
this.iterate1 = function(){
return this.secret1++;
}
this.iterate2 = function(){
return this.secret2++;
}
this.addSecrets = function(){
return this.secret1 + this.secret2;
}
};
var f3 = new myFunction3();
f3.secret1; // exposes the secret!
See the console logs at the bottom of this JSFiddle for more examples.
How can I have a function with both private and public vars/methods which retain their values and don't need to be called multiple times?
While the other answers are absolutely fine and correct, there is one more issue to consider when emulating OOP behaviour in javascript.
The function execution context issue will bite us hard when we will try to use a public method as a e.g. async. callback.
The magical this will point to a different object then we expect in the OOP world.
Of course there are ways to bind the context but why to worry about this after we define the 'class' in a non OOP js ;)
Here is a simple solution to this: Do not use this. Let the closure refactor this out ;)
var myFunction4 = function() {
// we could inherit here from another 'class' (object)
// by replacing `this` with e.g. `new SuperClass()`
var that = this;
// 'private' variables
var secret1 = 0;
var secret2 = 0;
// 'public' variables
that.somePublicVar = 4;
// 'private' methods
var somePrivateMethod = function(){
secret2 = 77;
that.somePublicVar = 77;
}
// 'public' methods
that.iterate1 = function(){
return secret1++;
}
that.iterate2 = function(){
return secret2++;
}
that.addSecrets = function(){
return secret1 + secret2;
}
return that;
};
var f = new myFunction4();
console.log( f.iterate1() ); // 0
console.log( f.iterate1() ); // 1
console.log( f.secret1 ); //undefined
console.log( f.somePublicVar ); //4
Try that (closures power!):
var myFunction3 = function() {
var secret1 = 0;
var secret2 = 0;
this.iterate1 = function(){
return secret1++;
}
this.iterate2 = function(){
return secret2++;
}
this.addSecrets = function(){
return secret1 + secret2;
}
};
var f3 = new myFunction3();
now only the methods are exposeds
Edited version:
If you don't wanna execute the main function every time you call sub-method, you can change a bit your approach and use the power of IIFE (immediately-invoked function expression)
var myFunction4 = (function() {
var secret1 = 0;
var secret2 = 0;
var iterate1 = function(){
return secret1++;
}
var iterate2 = function(){
return secret2++;
}
var addSecrets = function(){
return secret1 + secret2;
}
return {
iterate1: iterate1,
iterate2: iterate2,
addSecrets: addSecrets
}
}());
Then you can use this:
myFunction4.iterate1();
myFunction4.iterate2();
myFunction4.addSecrets();
Hope this helps you
I generally only use the factory pattern to create objects unless I absolutely need to have the performance benefits of prototypical inheritance.
Using the factory pattern also means you don't have to deal with the ever changing value of this in different contexts.
var factory = function() {
// internal private state
var state = {
secret1: 0,
secret2: 0
}
function iterate1(){
return state.secret1++;
}
function iterate2(){
return state.secret2++;
}
function addSecrets(){
return state.secret1 + state.secret2;
}
function __privateMethod() {
// this is private because it's not on the returned object
}
// this is the public api
return {
iterate1,
iterate2,
addSecrets
}
}
// create a secret module
var secret = factory()
console.log(
secret.iterate1(), // 0
secret.iterate2(), // 0
secret.addSecrets(), // 2
secret.secret1, // undefined
secret.secret2 // undefined
)
// you can even create more with the same factory
var secret2 = factory()
Why don't you try Revealing Module Pattern
var myFunction4 = function() {
var secret1 = 0,
secret2 = 0,
iterate1 = function(){
return secret1++;
},
iterate2 = function(){
return secret2++;
},
addSecrets = function(){
return secret1 + secret2;
};
// public functions and properties
return {
iterate1: iterate1,
iterate2: iterate2,
addSecrets: addSecrets,
}
}();
myFunction4.iterate1(); // is available
myFunction4.secret2; // is private and not available outside of myFunction4
Hope it helps
A basic pattern:
var myFunction = function() {
var that = this;
var secret1 = 0;
var secret2 = 0; // private
this.public1 = 0; // public
this.iterate1 = function(){
return secret1++;
}
this.iterate2 = function(){
return secret2++;
}
this.addSecrets = function() { // public
return privateMethod();
}
var privateMethod = function() { // private
return secret1 + secret2;
}
return this; // return function itself!
};
var myFn = new myFunction();
myFn.public1 // 0
myFn.secret1 // undefined
myFn.addSecrets();
I recommend you to read the excellent Learning JavaScript Design Patterns by Addy Osmani.
What I understand from your explanation as per your second snippet is that you need a sharedPrivate among the instantiated objects. You can not do this with classical object creation patterns like constructor, factory or module. This is possible by taking a private variable under closure in the prototype of the constructor so that it doesn't get reset each time an object is created and at the meantime the instantiated objects are provided with necessary methods to access, modify and share it privately.
function SharedPrivate(){
var secret = 0;
this.constructor.prototype.getSecret = function(){return secret}
this.constructor.prototype.setSecret = function(v){ secret = v;}
this.constructor.prototype.incrementSecret = function(){secret++}
}
var o1 = new SharedPrivate();
var o2 = new SharedPrivate();
console.log(o1.getSecret()); // 0
console.log(o2.getSecret()); // 0
o1.setSecret(7);
console.log(o1.getSecret()); // 7
console.log(o2.getSecret()); // 7
o2.incrementSecret()
console.log(o1.getSecret()); // 8
And another method of getting a similar result would be
function SharedPrivate(){
var secret = 0;
return {getS : function(){return secret},
setS : function(v){secret = v},
incS : function(){secret++}
};
}
sharedProto = SharedPrivate(); // secret is now under closure to be shared
var o1 = Object.create(sharedProto); // sharedProto becomes o1.__proto__
var o2 = Object.create(sharedProto); // sharedProto becomes o2.__proto__
o1.setS(7); // o1 sets secret to 7
console.log(o2.getS()); // when o2 access it secret is still 7
o2.incS(); // o2 increments the secret
console.log(o1.getS()); // o1 can access the incremented value

javascript failed to set private variables

I have created a class-like structure with a private variable. The code is as follows:
   
var sinan = function(){
var a = {ssss: 1};
return {
get: function(){
return a;
},
set: function(s){
a = {ssss: s}
}
}
}
When I do
sinan().get(); // outputs {ssss: 1}
sinan().set(2);
sinan().get(); // outputs {ssss: 1}
It didn't output {ssss: 2}. Does anyone know what is happening? Thanks.
Since your "class" is not singleton sinan() constructs new instance every time with a.sss being equal to 1.
What you want to do is to create only once instance and use it:
var s = sinan();
console.log( s.get() );
s.set(2);
console.log( s.get() );
Of course you can make sinon singleton too if you want. For example, here is a simple implementation with instance stored in closure:
var sinan = function () {
var instance;
return function () {
if (!instance) {
instance = function() {
var a = {ssss: 1};
return {
get: function () {
return a;
},
set: function (s) {
a.ssss = s
}
}
}();
}
return instance;
};
}();
So in this case sinan() === sinan(), i.e. sinan() returns the same object every time.
Demo: http://jsfiddle.net/r07wgyjt/
Your problem is that each time you call sinan(), a new sinan instance is created, so it's the same as :
var s1 = sinan();
s1.get(); // 1
var s2 = sinan() ;
s2.set(2); // 2
var s3 = sinan();
s3.get(); // 3
You should be doing :
var s1 = sinan();
s1.get(); // 1
s1.set(2); // 2
s1.get(); // 2

javascript access "this" in function constructor

I'm trying to create a function constructor:
var obj = function() {
this.num = 2;
this.func = function() {
// need to access the **instance** num variable here
};
};
var instance = new obj();
I need to access the instance properties from a propery (which is the function func) of the object. But it doesn't work, since this is always the current function..
Store this in a variable which func can access:
var obj = function() {
var _this = this;
_this.num = 2;
_this.func = function() {
console.log(_this.num);
};
};
Please, use well-known approach, store this into separate field:
var obj = function() {
self = this;
self.num = 2;
self.func = function() {
alert(self.num);
// need to access the **instance** num variable here
};
};
var instance = new obj();
This is the pattern I use for the problem:
var obj = function(){
var self = this;
this.num = 2;
this.func = function() {
console.info(self.num);
};
};
var instance = new obj();
The variable self now can be accessed in all function of obj and is always the obj itself.
This is the same then:
var obj = function(){
var self = this;
self.num = 2;
self.func = function() {
console.info(self.num);
};
};
var instance = new obj();
You can do it using the Custom Constructor Functions, used to create a custom constructor and it's accessed without any problem, try it:
var Obj = function () {
this.num = 2;
this.func = function () {
alert("I have " + this.num);
return "I have " + this.num;
};
};
var instance= new Obj();
instance.func();//will return and show I have 2

Pass reference of main object to another object

I created this simplified version of some code I'm dealing with. I need to figure out how to pass a reference of an instantiated object to another object that has been created by this object. I can't get the reference to the main object "self" to be passed to the second object and actually be able to call a function on it. Hopefully the code will make it more clear:
var app = app || {};
(function (m, $, undefined) {
m.Counter = function () {
var self = this;
var pub = {};
pub.total = 0;
pub.add = function () {
pub.total++;
};
pub.subtract = function () {
pub.total--;
};
pub.status = function () {
console.log(pub.total);
};
pub.spawn = function () {
var sp = new app.modules.Obj(self);
return sp;
};
return pub;
};
m.Obj = function (counter) {
var pub = {};
pub.add = function () {
counter.add();
};
return pub;
};
}(app.modules = app.modules || {}));
var c = new app.modules.Counter();
c.add();
c.add();
c.add();
c.status();
d = c.spawn();
d.add();
c.status();
What I would want to have happen is that d.add() would increment the total of c. So the output would be 3 for the first c.status() call and then 4 for the output of the second c.status();

Categories

Resources