I'm fairly new to JavaScript and TypeScript.
As far as I'm concerned, TypeScript is compiled into regular JavaScript.
Coming from C#, where objects are passed by reference (if they're not primitive types or structs). I've written some TypeScript code to test something:
interface IRunner {
run(): string;
}
class TestDI {
private readonly Runner: IRunner;
constructor(runner: IRunner) {
this.Runner = runner;
}
test(): void {
console.log('Result of runner: ' + this.Runner.run());
}
}
class FooRunner implements IRunner {
run(): string {
return 'Foo';
}
}
class BarRunner implements IRunner {
run(): string {
return 'Bar';
}
}
let runner: IRunner;
runner = new FooRunner();
const SUT: TestDI = new TestDI(runner);
// Expected output: Foo
// Actual output: Foo
console.log(runner.run());
// Expected output: Foo
// Actual output: Foo
SUT.test();
runner = new BarRunner();
// Expected output: Bar
// Actual output: Bar
console.log(runner.run());
// Expected output: Bar
// Actual output: Foo
SUT.test();
In the code above I've passed an instance of IRunner
interface into a class c-tor, then, a field of my class is populated with whatever I passed in the c-tor.
Later in the code I change the variable I passed into the c-tor, however, when I call the test
function Runner
field of my class seems to not reflect any changes done on the original variable I passed when creating an instance of my TestDI
class.
In C# the code I've written would behave as I expect it to. But here it's not.
What's going on?