node.js - Typescript: Pass by value or by reference -


i have file:

object.ts:

export const myobject {     prop1: "prop1",     prop2: "prop2",     ...     ... } 

and have class

my-class.ts

export class myclass {     private obj: any;      constructor(obj: any) {         this.obj = obj     } } 

and have file:

main.ts

import { myobject } "object"; import { myclass } "my-class";   let class1 = new myclass(myobject); let class2 = new myclass(myobject); let class3 = new myclass(myobject); 

will creating instances of class myclass way pass object myobject value or reference. in way, myobject object copied 3 times; i'm concerned memory.

udpate

consider other example:

my-class.ts

export class myclass {     private obj: any;      constructor(obj: any) {         this.obj = obj     }     getvalue(str: string) {         return obj[str];     } } 

function1.ts

import { myobject } "object";  let myclass = new myclass(myobject)  export function fn1(str: string) {     return myclass.getvalue(str); } 

function2.ts

import { myobject } "object";  let myclass = new myclass(myobject)  export function fn2(str: string) {     return myclass.getvalue(str); } 

main.ts

import { fn1 } "function1"; import { fn2 } "function2";  console.log(fn1(str)); console.log(fn2(str)); 

will second example create 2 copies of myobject?

for first example, myobject created once, since argument passed reference (or pointers objects passed value).

for second example, there nothing changed javascript's evaluation strategy, myobject still same instance. if @ compiled javascript code find function1.ts , function2.ts wrapped in 2 different functions, makes myclass become 2 different variables.


Comments