“Sintaks kelas JS” Kode Jawaban

Kelas JavaScript

class ClassMates{
	constructor(name,age){
    	this.name=name;
      	this.age=age;
    }
  	displayInfo(){
    	return this.name + "is " + this.age + " years old!";
    }
}

let classmate = new ClassMates("Mike Will",15);
classmate.displayInfo();  // result: Mike Will is 15 years old!
Spotted Tailed Quoll

Kelas JavaScript

// Improved formatting of Spotted Tailed Quoll's answer
class Person {
	constructor(name, age) {
		this.name = name;
		this.age = age;
	}
	introduction() {
		return `My name is ${name} and I am ${age} years old!`;
	}
}

let john = new Person("John Smith", 18);
console.log(john.introduction());
Nathan uses Linux

Kelas JS

function Animal (name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  console.log(`${this.name} makes a noise.`);
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

// For similar methods, the child's method takes precedence over parent's method
Dead Donkey

Kelas JavaScript

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100
HimansaE

Kelas JavaScript

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  get area() {
    return this.calcArea();
  }

  calcArea() {
    return this.height * this.width;
  }
}

const square = new Polygon(10, 10);

console.log(square.area);
Perfect Pheasant

Sintaks kelas JS

// method 1

function nested(name , age , color){
    this.name = name;
    this.details = { 
        age : age,
        color : color
    }
}

let nestedObj = new nested( "Elroi" , 22 , "blue");
 console.log(nestedObj)


// method 2
class Nested2{
    constructor(name , age , color){
        this.name = name;
        this.details = {
            age : age,
            color : color
        }
    };

    displayInfo(){
        console.log(`${this.name} ${this.details.age} ${this.details.color} `)
    } 
}

let aaa  = new Nested2("Ean" , 14 , "black");
aaa.displayInfo(); 
Confused Crossbill

Jawaban yang mirip dengan “Sintaks kelas JS”

Pertanyaan yang mirip dengan “Sintaks kelas JS”

Lebih banyak jawaban terkait untuk “Sintaks kelas JS” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya