简体   繁体   English

Typescript Class 带私有变量

[英]Typescript Class with private variables

Need help to write following javascript code in typescript, it is a simple class with two public functions:需要帮助在 typescript 中编写以下 javascript 代码,它是一个具有两个公共功能的简单 class:

var Myclass =   (function  ()
{
var teststr = ['ein test','noch ein test'];

function Myclass (){
    this.test();
}
function getStr (id) {
    return teststr[id];
}
Myclass.prototype.test = function ()
{
    console.log(getStr(0))
    this.test1();
}
Myclass.prototype.test1 = function ()
{
    console.log(getStr(1))
}
return Myclass;
})();
var instMyClass = new Myclass();
  • var instMyClass call the constructor, than the constructor call public function test. var instMyClass调用构造函数,比构造函数调用public function测试。
  • function test give out the first element of private array teststr and call public function test1 function test 给出私有数组 teststr 的第一个元素并调用 public function test1
  • function test1 give out the second elemement of private array teststr function test1 给出私有数组teststr的第二个元素

i try this solution, bur typescript compilier shows errors我尝试这个解决方案,bur typescript 编译器显示错误

class Myclass {
private teststr:Array<string> = ['ein test','noch ein test'];
constructor() {
    this.test();
}
function getStr() {
    return teststr[id];
}
test() {
console.log(getStr(0));
    this.test1();
}
test1(str:string) {
console.log(getStr(1));
}
}

let instMyclass = new Myclass();

if i try a private function with a form.submit, than the function is undefined:如果我尝试使用 form.submit 的私有 function,那么 function 是未定义的:

class Ticket {

private form: HTMLFormElement;

constructor() {

    this.form = document.forms[0]!
    this.form.onsubmit = this.submit;
}
private setUser (user: TicketUser):void {
    console.log('ticket setUser',user);
}
public submit ():any {
    console.log('ticket submit');
    this.setUser({name:'stefan',age:100});
    return false;
}
}

Can you try with the typescript code below . 您可以尝试以下打字稿代码吗? Updated my answer 更新了我的答案

ts file ts文件

class Ticket {

    private form: HTMLFormElement;

    constructor(elem: HTMLFormElement) {

        this.form = elem;
        //this.form.onsubmit = this.submit();
    }
    private setUser(user: TicketUser): void {
        console.log('ticket setUser', user);
    }
    public submit(): any {
        console.log('ticket submit');
        this.setUser({ name: 'stefan', age: 100 });
        return false;
    }
}

class TicketUser {

    name: string;
    age: number;
}

window.onload = () => {
    var btn = document.getElementById("btn");
    btn.onclick = function () {
        var form = document.forms[0];
        var ticket = new Ticket(form);
        form.onsubmit = ticket.submit();

    }
};

HTML 的HTML

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />

</head>
<body>
    <h1>TypeScript test</h1>

    <form id="myform" action="#"></form> <br />
    <button id="btn">click me</button>
    <script src="test.js"></script>
</body>
</html>

You can use getter/setter for what you are trying to do. 您可以使用getter / setter进行尝试。
Firstly you forgot the 'this' to call variables and functions withing class. 首先,您忘记了“ this”与类一起调用变量和函数。
Secondly you don't use function, you use private, publict and protected to declare them. 其次,您不使用函数,而是使用private,publict和protected来声明它们。
See the example below on how to build, instantiate and use a class. 请参阅以下示例,了解如何构建,实例化和使用类。

class Myclass {
private teststr: Array<string> = ['ein test','noch ein test'];

constructor() {
    this.test();
}

public getStr(id): string {
    return this.teststr[id];
}

public setStr(str: string) {
    this.teststr.push(str);
}

private test() {
    console.log('This works, calling withing class functions within class');
}

private test1(str:number) {
    console.log(this.getStr(1));
}
}

let instMyclass = new Myclass();
instMyclass.setStr('Another String');
let x = instMyclass.getStr(2);
console.log(x);

If you have tsc compiler install do this: 如果安装了tsc编译器,请执行以下操作:

tsc myfilename.tsc
node myfilename.js

and you should see the output. 您应该会看到输出。

You can now use private access fields in TypeScript:您现在可以在 TypeScript 中使用私有访问字段

class Person {
  #address = '221B, Baker Street, London';
  
  checkAddress(address: string) {
      return this.#address === address;
  }
}

Read more about this in my article here .在我的文章中阅读更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM