简体   繁体   English

我转到了 javascript 学习班,下面的代码似乎不起作用

[英]I moved to learning class in javascript and the below code doesn't seem to work

I moved from functions to javascript classes.我从函数转移到 javascript 类。 And my first example I tried, doesn't seem to work and I can't find why?我尝试的第一个示例似乎不起作用,我找不到原因? Here I expect output to be num1 + num2 as a string whenever I click the "Click" button.在这里,每当我单击“单击”按钮时,我都希望输出为 num1 + num2 作为字符串。

 class Sum{ constructor(num1, num2){ this.num1 = num1; this.num2 = num2; } add(){ this.result = "num1 + num2"; } displayResult(){ document.getElementById("demo").innerText = this.result; } } const s = new Sum("a", "b"); document.getElementById("button").addEventListener("click", () => { s.add(); s.displayResult(); });
 <button id="button">Click</button> <p id="demo"></p>

So a couple of things went wrong here:所以这里出现了一些问题:

  1. Don't use the literal string "this.num1 + this.num2" but use the expression that take the variables and sum them together this.num1 + this.num2 .不要使用文字字符串"this.num1 + this.num2"而是使用获取变量并将它们加在一起的this.num1 + this.num2
  2. You used event listener on element that is not appeared on the screen, so how can you click it?您对未出现在屏幕上的元素使用了事件侦听器,那么您如何单击它? You probably meant to use the click event on the id button and not the demo .您可能打算在 id button上使用click事件而不是demo
  3. As a rule of thumb, I don't think it's good to involve UI logic with your classes logic.根据经验,我认为将 UI 逻辑与类逻辑结合起来并不好。 For future use, it usually better to keep them separated.为了将来使用,通常最好将它们分开。

Good Luck祝你好运

 class Sum { constructor(num1, num2) { this.num1 = num1; this.num2 = num2; } add() { this.result = this.num1 + this.num2; } } const s = new Sum(6, 7); document.getElementById("button").addEventListener("click", () => { s.add(); displayResult(s.result); }); function displayResult(result) { document.getElementById("demo").innerText = result; }
 <button id="button">Click</button> <p id="demo"></p>

You don't nee the quotes in the add function and you are missing.您不需要 add 函数中的引号,并且您丢失了。 this before the nums this在 nums 之前

this.result = this.num1 + this.num2

But as you are passing in strings to the constructor it will just concatenated the values so the output will be ”ab”但是当您将字符串传递给构造函数时,它只会连接这些值,因此输出将为“ab”

If those were supposed to be variables it should be:如果这些应该是变量,它应该是:

var a = 5;
var b = 7;

const s = new Sum(a, b);

Here your code:这里你的代码:

 class Sum { constructor(num1, num2) { this.num1 = num1; this.num2 = num2; } add() { this.result = this.num1 + this.num2; } displayResult() { document.getElementById("demo").innerText = this.result; } } const s = new Sum("a", "b"); document.getElementById("button").addEventListener("click", () => { s.add(); s.displayResult(); });
 <button id="button">Click</button> <p id="demo"></p>

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

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