Try the below code. name should be set as “this.name = name
“. and show function should log this.name
instead of this.username
.
class Student {
constructor(name) {
this.name = name;
}
show() {
console.log(this.name);
}
}
Add the below function.
function show() {
let name = document.getElementById("userName").value;
var st = new Student(name);
st.show();
}
Call show()
function on button click instead of emp.show()
<body>
<input type="text" id="userName">
<button onclick="show()">Click</button>
</body>
<script src="script.js"></script>
You are seeing the variable name with a property?
constructor(name){
name=this.name; <-- you have this reversed
}
You are referencing a property you never set
show(){
console.log(this.username) <-- what is username?
}
}
You are reading the value when the page loads
let name=document.getElementById('userName').value;
Basic idea using getter and setter
class Student {
_name = "unknown"
constructor() {
}
set name(name) {
this._name = name
}
get name() {
return this._name
}
reverseName() {
return [...this._name].reverse().join("");
}
}
const st = new Student();
document.getElementById("userName").addEventListener("input", function (e) {
st.name = e.target.value;
});
document.getElementById("show").addEventListener("click", function (e) {
console.log(st.name);
});
document.getElementById("rev").addEventListener("click", function (e) {
console.log(st.reverseName());
});
<label for="username">Name:</label>
<input type="text" id="userName">
<button type="button" id="show">Click</button>
<button type="button" id="rev">Reverse</button>
Please check if this helps:
class Student{
constructor(name){
this.name=name;
}
show(){
console.log(this.name);
}
}
function empShow(){
let name = document.getElementById('userName').value;
var st = new Student(name);
return st.show();
}
<body>
<input type="text" id="userName">
<button onclick="empShow()">Click</button>
</body>
<script src="script.js"></script>
HTML code
As you can this how to call the class method from HTML
<body>
<input type="text" id="userName">
<button onclick="st.show()">Click</button>
</body>
<script src="script.js"></script>
I want to display the username in console
Javascript code
class Student{
constructor(name){
this.name=name;
}
show(){
console.log(this.name)
}
}
let name=document.getElementById('userName').value;
var st=new Student(name);
I still got the same error.
you can write another function and call show function. Then call the newly added function onclick. There is another issue with the class class constructor. set the name as ‘this.name = name’
did u change this.name = name; in constructor? and console.log(this.name); in show() function. please compare the code in class.
sorry @epascarello for sharing this wrong code please check once again I am updating …