1
传递我有这个文件:打字稿:通过值或引用
object.ts:
export const myObject {
prop1: "prop1",
prop2: "prop2",
...
...
}
,我有这个类
我-class.ts
export class MyClass {
private obj: any;
constructor(obj: any) {
this.obj = obj
}
}
,我有这个文件:
个main.ts
import { myObject } from "object";
import { MyClass } from "my-class";
let class1 = new MyClass(myObject);
let class2 = new MyClass(myObject);
let class3 = new MyClass(myObject);
将创建类MyClass
这样的实例由值或参考传递对象myObject
。以另一种方式,将myObject
对象被复制三次;我很关心记忆。
UDPATE
考虑这个其他例子:
我-class.ts
export class MyClass {
private obj: any;
constructor(obj: any) {
this.obj = obj
}
getValue(str: string) {
return obj[str];
}
}
function1.ts
import { myObject } from "object";
let myClass = new MyClass(myObject)
export function fn1(str: string) {
return myClass.getValue(str);
}
function2.ts
个import { myObject } from "object";
let myClass = new MyClass(myObject)
export function fn2(str: string) {
return myClass.getValue(str);
}
main.ts
import { fn1 } from "function1";
import { fn2 } from "function2";
console.log(fn1(str));
console.log(fn2(str));
将在第二个例子中创建的myObject
两个副本?
我打算假设它具有与[Javascript评估策略]相同的评估策略(https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) –
它是通过引用。是的,这是一个JavaScript问题。不是TypeScript。 – unional
@unional可以请检查我更新的问题吗? – m2008m1033m