Lets say we have two objects and a using function like this:
function using(namespace, scope){
for(x in namespace){
scope[x] = namespace[x];
}
}
function fooClass(){
this.foo = function(){
console.log("foo");
}
this.bar = function(){
console.log("bar");
}
}
var myFoo = new fooClass();
function barClass(){
using(myFoo, this);
}
var myBar = new barClass();
myBar.foo();
In this example, it carries over everything from fooClass in to barClass. This is a small example of a vary large scale situation I am looking into doing this. The namespace
that I am working with in my actual use case is rather large. I know javscript passes by reference for all objects. Some items from the namespace
are arrays of objects or individual objects that contain arrays of objects or simply just functions. Most primitive variables are private so they should not carry over.
I am curious how much data I am duplicating and how much data I am referencing? Objects stored in the namespace
should be referenced, but what about functions? Are they copied like a primitive variable or referenced? More so, should I be concerned about memory consumption with this using()
function?
The main reason I wrote it was because sometimes I'm having to make a call to a deeply nested object and this makes the code more readable, but I do not want to do this if I am sacrificing memory.
When copying namespace
properties to space
using for ... in
, all primitive and object reference values are duplicated so they take up twice as much memory.
JavaScript object values (which include function objects) are held in variables as references to "somewhere" in memory that holds object properties. The copy operation only duplicates the reference, not underlying property names and values or function code, so additional memory consumed by creating a copy is similar to copying a primitive value.
For the use case presented however, you may wish to extend the base myFoo
object so it is inherited by barClass
instances. This does mean, of course, that no snapshot of mFoo
is taken, and myBar
instances would inherit any future changes to myFoo
.
ES5 example:
let myFoo = {foo: "foo"};
function myBar() {
this.bar = "bar";
}
myBar.prototype = Object.create( myFoo);
myBar.constructor = myBar;
let bar = new myBar();
console.log( bar.foo);
ES2015 requires a little more work to create an intermediate function to extend an object which is not a function:
let myFoo = {foo: "foo"};
function interFoo() {
};
interFoo.prototype = myFoo;
class myBar extends interFoo {
constructor() {
super();
this.bar = "bar";
}
}
let bar = new myBar();
console.log( bar.foo);
Note that if you extend fooClass
directly (the constructor of myFoo
), creating instances of barClass
would recreate all properties locally by calling forClass
as the super class constructor - which is probably not what you want.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments