variable visibility in javascript - javascript

I am struggling to understand how variables are referenced and stay alive in Javascript. In the following I have two types of object, a Note and an IntervalBuilder which takes a Note and creates
a second Note.
function Note() {
this.key = 1 + Math.floor( Math.random() * 13); // from 1 to 13 inclusive
this.setKey = function setKey(i) { key = i; };
this.getKey = function getKey() { return this.key; } ; // {return key} is a ReferenceError!!
}
function IntervalBuilder() {
this.setPerfectFifth = function setPerfectFifth(root) {
this.fifth = new Note();
console.log("this.fifth: " + this.fifth);
this.y = root.key;
console.log("root.key: " + root.key );
console.log("y: " + this.y );
this.fifth.setKey( this.y + 4 );
return this.fifth;
};
}
With the above I can now do this:
var x = new Note();
var ib = new IntervalBuilder();
ib.setPerfectFifth(x);
However, the instance ib now has a member named fifth! What I was hoping for was that I could assign the return value (a Note) from setPerfectFifth to a variable and let fifth vanish. How is that done?
Many thanks for any help, I find lots of this very confusing.
Gerard

Since you titled your quesion variable visibility in javascript what is basically going on is: In this.fifth = new Note(); the keyword this references the instance (the ib of var ib = new ...). So you attach your newly created Note to the instance. In JavaScript, as long as a variable can be reached starting with the global Object (window, when you think of a graph), it won't get garbage-collected away.
What you want is: var fith = new Note(), which will create a local variable which will get freed as soon as the function execution ends. Clearly, every usage of this.fifth then has to be replaced by just fith.

I do not know exactly what you want to achieve, but I think you want the following code structure:
// ==============================
// NOTE "CLASS"
// ==============================
var Note = (function () {
// Constructor
function Note() {
this._key = 1 + Math.floor( Math.random() * 13);
}
// Getter
Note.prototype.getKey = function () {
return this._key;
};
// Setter
Note.prototype.setKey = function (i) {
this._key = i;
};
return Note;
})();
// ==============================
// INTERVAL BUILDER "CLASS"
// ==============================
var IntervalBuilder = (function () {
// Constructor
function IntervalBuilder() {}
// Private members
var fifth = null,
y = 0;
// Setter
IntervalBuilder.prototype.setPerfectFifth = function (root) {
fifth = new Note();
y = root.getKey();
fifth.setKey(y + 4);
return fifth;
};
return IntervalBuilder;
})();
// ==============================
// CLIENT CODE
// ==============================
var x = new Note(),
ib = new IntervalBuilder();
ib.setPerfectFifth(x);

Related

Closures: Scope Chain Variables - Not sure how variables link up

Really new to Javascript. This code is taken from MDN.
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var s = sum(1);
var s1 = s(2);
var s2 = s1(3);
var s3 = s2(4);
console.log(s3) //log 20
When I try to input different variable names (EX below) they don't seem to work and I don't understand how everything links up together to spit out the answer 20.
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var w = sum(1);
var x = s(2);
var y = s1(3);
var z = s2(4);
console.log(s3) //log 20
When I change it to this it also does not work. The console tells me that sa is not defined
// global scope
var e = 10;
function sm(a){
return function sa(b){
return function sb(c){
// outer functions scope
return function sc(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var s = sm(1);
var s1 = sa(2);
var s2 = sb(3);
var s3 = sc(4);
console.log(sc) //log 20
I can keep throwing out more examples that don't work. Someone, please help me understand how the first example works.
function sm(a){
return function sa(b){
return function sb(c){
// outer functions scope
return function sc(d){
// local scope
return a + b + c + d + e;
}
}
}
}
The function sm is taking one argument and is returning a function which takes one argument. The function sm returns is not named sb. Try to think of it as the return value of sm .
So, when you do
var s = sm(1);
The returned function is stored in the variable s
Now if you want to run the second function (sa inside sm) you need to invoke s.
var s1 = s(2);
The returned function (sb) is stored inside varibale s1.
Similarly,
var s2 = s1(3);
var s3 = s2(4);
console.log(s3); // 20

clone javascript function, closure scope

I have this closure :
function CFetchNextData(ofs, pag, fetchFunction) {
var offset = ofs;
var limit = pag;
return function(options, cb) {
//do stuff to create params
fetchFunction(params, cb);
offset += limit;
};
}
I then create a variable this way:
var fetchInfo = CFetchNextData(0, 10, specificFetchFunction);
fetchInfo(options, myCB);
So that everytime I call fetchInfo, pagination is automatically set to the next set of data. That works great, althought
I'd like to have multiple instance of : "fetchInfo", each one having its own scope.
var A = fetchInfo; // I'd like a clone with its own scope, not a copy
var B = fetchInfo; // I'd like a clone with its own scope, not a copy
I could do:
var A = new CFetchNextData(ofs, pag, fetchFunction);
var B = new CFetchNextData(ofs, pag, fetchFunction);
But obviously I would have to setup "ofs" and "pag" each time, whereas by cloning fetchInfo, I'd have a stable pagination, set only once and for good.
Do you know how to achieve that ?
Thanks in advance
There isn't a concept of cloning a function in JavaScript. You need to call CFetchNextData (or another function) multiple times if you want to create multiple closures.
You could have CFetchNextData return a factory function instead of returning the actual function. But I'm not sure that's really an improvement.
function CFetchNextDataFactory(ofs, pag, fetchFunction) {
return function() {
var offset = ofs;
var limit = pag;
return function(options, cb) {
//do stuff to create params
fetchFunction(params, cb);
offset += limit;
};
};
}
var fetchInfoFactory = CFetchNextData(0, 10, specificFetchFunction);
var A = fetchInfoFactory();
var B = fetchInfoFactory();
This may not answer all of your question but just to pitch in , you could try assigning your parameters to a default / fallback value which will allow you to avoid setting ofs and pag each declaration . Below is a prototype of what I came up with . Its using oop :
class CFetchNextData {
constructor(ofs, pag){
this.OFS = 1; //default value
this.PAG = 10; //default value
this.ofs = ofs;
this.pag = pag;
if(ofs == null || ofs == undefined){
this.ofs = this.OFS;
}
if(pag = null || pag == undefined){
this.pag = this.PAG;
}
}
fetchInfo(){
var data = this.ofs += this.pag;
return data;
}
}
var task1 = new CFetchNextData(); // Falls back to default values..
var task2 = new CFetchNextData(32,31); // Uses values from specified in args...
document.write(task1.fetchInfo() + "\n")
document.write(task2.fetchInfo())
Hope this helps...

How to define a javascript internal method that needs to be accessible from inside obj and out

I'm trying to fully grasp JavaScript inheritance and encapsulation. Take the following example (and here is a fiddle of it):
myPage = {
someObj: function() {
var x = 0;
//PRIVATE: increment by 10
var inc10 = function() {
x = x+10;
};
//PUBLIC: increment
this.inc = function() {
x = x+1;
};
//PUBLIC: decrement
this.dec = function() {
x = x-1;
};
//PUBLIC: output the current value of x
this.getValue = function() {
return x;
}
inc10(); //as soon as obj1 is created lets add 10
this.inc(); //as soon as obj1 is created lets add 1 more
}
};
obj1 = new myPage.someObj(); //x starts out at 11
// obj1.inc10(); won't work because it's private, excellent
obj1.dec();
obj1.inc();
alert(obj1.getValue());
My question is about the inc() method. I need it to be callable from inside and outside of the object. Is this the proper way to do that?
I need it to be callable from inside and outside of the object. Is this the proper way to do that?
Your script does seem to work as expected already, you are calling the method as this.inc() in your constructor perfectly fine - not sure why it needs improvement.
You could however define it as a local function, which you then are going to export as a method - and have it still available "inside" as a local variable:
function SomeObj() {
// local declarations:
var x;
function inc10() {
x = x+10;
}
function inc1() {
x = x+1;
}
// exported as property:
this.inc = inc1; // <== the function from above, not a literal
this.dec = function() {
x = x-1;
};
this.getValue = function() {
return x;
};
// initialisation:
x = 0;
inc10();
inc1(); // this.inc() would still work
}
To call function from inside and outside without attaching it to an obj.
This should work ...
myPage = function() {
var x = 0;
//PRIVATE: increment by 10
var inc10 = function() {
x = x+10;
};
//PUBLIC: increment
this.inc = function() {
x = x+1;
};
//PUBLIC: decrement
this.dec = function() {
x = x-1;
};
//PUBLIC: output the current value of x
this.getValue = function() {
return x;
}
inc10(); //as soon as obj1 is created lets add 10
this.inc(); //as soon as obj1 is created lets add 1 more
};
obj1 = new myPage; //x starts out at 11
// obj1.inc10(); won't work because it's private, excellent
obj1.inc();
alert(obj1.getValue());

Return a number from a constructor

I've been my banging head against the wall with the above question. Let's say I have the following class:
function Counter() {...}
so when I call the constructor:
var c= new Counter();
console.log(c); //return 0
furthermore If I created the following method:
Counter.prototype.increment = function() {
return this += 1;
};
it should increment c by 1 for every call
c.increment(); // return c=1
c.increment(); // return c=2
so far I have come up with:
function Counter(){return Number(0)}
but still returns Number{} not a zero...
Any thoughts?
Thanks in advance!
JavaScript doesn't allow for a custom Object type to directly imitate a primitive value. It also doesn't allow this to be assigned a new value.
You'll have to instead store the value within a property:
function Counter() {
this.value = 0;
}
var c = new Counter();
console.log(c); // Counter { value: 0 }
And, increment the value from it:
Counter.prototype.increment = function () {
this.value += 1;
};
c.increment();
console.log(c.value); // 1
Though, you can at least specify how the object should be converted to a primitive with a custom valueOf() method:
Counter.prototype.valueOf = function () {
return this.value;
};
console.log(c.value); // 1
console.log(c + 2); // 3
You can't return a value from the constructor because you instantiate it using the new keyword, this gives you a new instance of the object.
Store a property and increment that instead:
function Counter() {
this.count = 0;
}
Counter.prototype.increment = function() {
this.count++;
return this.count;
};
var c= new Counter();
console.log( c.increment() ); // 1
console.log( c.increment() ); // 2
console.log( c.increment() ); // 3
This is your problem:
Counter.prototype.increment = function() {
return this += 1;
};
this is an object, += is not defined for objects.

Get all instances of class in Javascript

I thought there would already be an answer for this but I can't seem to find one..
How can I run a particular class method on all instances of this class in Javascript?
This has to be done in a situation where I do not know the names of the instances.
I think I could use some sort of static variable inside my class to store all instances, but this doesn't seem to exist in JS
So how to call my method on all existing instances of my class?
Note : just for clarification : I'm not speaking about CSS classes, I'm speaking about objects.
Edit : By Class in Javascript, I mean the creation of a new object on a function:
function something()
{
}
var instance = new something();
You can create a static array and store it on your constructor function:
MyClass.allInstances = [];
MyClass.allInstances.push(this);
However, you need some way to figure out when to remove instances from this array, or you'll leak memory.
In Chrome 62+ you can use queryObjects from the console API - which will not work in native JavaScript code but in the console so it's great for debugging.
class TestClass {};
const x = new TestClass();
const y = new TestClass();
const z = new TestClass();
queryObjects(TestClass)
You'll have to provide a custom implementation.
I would do something like this :
function Class() {
Class.instances.push(this);
};
Class.prototype.destroy = function () {
var i = 0;
while (Class.instances[i] !== this) { i++; }
Class.instances.splice(i, 1);
};
Class.instances = [];
var c = new Class();
Class.instances.length; // 1
c.destroy();
Class.instances.length; // 0
Or like this :
function Class() {};
Class.instances = [];
Class.create = function () {
var inst = new this();
this.instances.push(inst);
return inst;
};
Class.destroy = function (inst) {
var i = 0;
while (Class.instances[i] !== inst) { i++; }
Class.instances.splice(i, 1);
};
var c = Class.create();
Class.instances.length; // 1
Class.destroy(c);
Class.instances.length; // 0
Then you could loop through all instances like so :
Class.each = function (fn) {
var i = 0,
l = this.instances.length;
for (; i < l; i++) {
if (fn(this.instances[i], i) === false) { break; }
}
};
Class.each(function (instance, i) {
// do something with this instance
// return false to break the loop
});
Sorry for such a late reply, but I found myself trying to achieve this and I think this may be a simpler answer.
Say you want all instances of class MyClass, only get instances created at top window level (not including instances created inside a closure):
for (var member in window)
{
if (window[member] instanceof MyClass)
console.info(member + " is instance of MyClass");
}
Keyword 'static' could be used in classes now (but check support), ...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
class Point{
constructor(x, y){
this.x = x;
this.y = y;
Point.all.push(this);
}
destroy(){
let i = Point.all.indexOf(this);
Point.all.splice(i, 1);
}
static all = [];
}
var p1 = new Point(1, 2);
var p2 = new Point(54, 33);
var p3 = new Point(297, 994);
console.log(JSON.stringify(Point.all)); //[{"x":1,"y":2},{"x":54,"y":33},{"x":297,"y":994}]
p2.destroy();
console.log(JSON.stringify(Point.all)); //[{"x":1,"y":2},{"x":297,"y":994}]
You'll need to store a list of instances yourself:
function someClass(param) {
// add to all
if (this.constructor.all === undefined) {
this.constructor.all = [this];
} else {
this.constructor.all.push(this);
}
// set param
this.logParam = function() { console.log(param); };
}
var instance1 = new someClass(1);
var instance2 = new someClass(2);
for (var i = 0; i < someClass.all.length; i++) {
someClass.all[i].logParam();
}
If memory leaks are a concern then you can create a method for deleting instances when you are done with them:
function someClass(param) {
...
this.destroy = function() {
var all = this.constructor.all;
if (all.indexOf(this) !== -1) {
all.splice(all.indexOf(this), 1);
}
delete this;
}
}

Categories