[英]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:所以这里出现了一些问题:
"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
。click
event on the id button
and not the demo
.button
上使用click
事件而不是demo
。 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.