打字稿:按价值或按参考传递

时间:2017-04-05 18:39:27

标签: node.js typescript

我有这个文件:

object.ts:

<!DOCTYPE html>
<html>

<head>
  <link data-require="font-awesome@*" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div class='bold'>Incorrect shadow</div>
  </br>
  <div>
    <span class="fa-stack fa-3x">
        <i id='blah' class="fa fa-circle-o fa-stack-2x"></i>
        <strong class="fa-stack-1x">1</strong>
      </span>
  </div>
  </br>
  <div class='bold'>Produces an Oval - Not a Circle</div>
  </br>
  <div class="icon-wrapper">
    <i class="fa page-number-core page-number-dark">
            <span class="page-number-text page-number-text-light">1</span>
        </i>
  </div>
  <br/><br/>
  <div class='bold'>Produces an Circle with Shadow but not for a #</div>
  </br>
  <div class="icon-wrapper">
    <i class="fa fa-comment page-number-core page-number-dark">
            <span class="page-number-text page-number-text-light fix-editor">&nbsp;</span>
        </i>
  </div>
  </br>
  <div>
    <a href="http://codepen.io/Onomicon/pen/iDfld">Source of Circle with Shadow</a>
  </div>
</body>

</html>

我有这个班级

MY-class.ts

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

我有这个文件:

main.ts

export class MyClass {
    private obj: any;

    constructor(obj: any) {
        this.obj = obj
    }
}

将创建类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对象是否会被复制三次;我很关心记忆。

UDPATE

考虑另一个例子:

MY-class.ts

myObject

function1.ts

export class MyClass {
    private obj: any;

    constructor(obj: any) {
        this.obj = obj
    }
    getValue(str: string) {
        return obj[str];
    }
}

function2.ts

import { myObject } from "object";

let myClass = new MyClass(myObject)

export function fn1(str: string) {
    return myClass.getValue(str);
}

main.ts

import { myObject } from "object";

let myClass = new MyClass(myObject)

export function fn2(str: string) {
    return myClass.getValue(str);
}

第二个示例是否会创建import { fn1 } from "function1"; import { fn2 } from "function2"; console.log(fn1(str)); console.log(fn2(str)); 的两个副本?

1 个答案:

答案 0 :(得分:3)

对于您的第一个示例,myObject将只创建一次,因为参数是通过引用传递的(或者指向对象的指针是按值传递的)。

对于您的第二个示例,JavaScript的评估策略没有任何变化,因此myObject仍然是同一个实例。但是如果你看看编译好的JavaScript代码,你会发现function1.ts和function2.ts将包含在两个不同的函数中,这使myClass成为两个不同的变量。