JS OOP: 09. Prototype
by istiq20
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Prototype</title>
</head>
<body>
<script>
function Person() {
this.firstName = ""
this.lastName = ""
this.sayHello = function (name) {
console.log(`Hello ${name}, my name is ${this.firstName}`);
}
}
// menambahkan property ke prototype
Person.prototype.sayBye = function (){
console.info("Good Bye");
}
Person.prototype.run = function (){
console.info(`${this.firstName} is running`);
}
const eko = new Person();
eko.firstName = "Eko";
const budi = new Person();
budi.sayBye = function (){
console.log("Sampai jumpa");
}
console.log(eko);
console.log(budi);
// mengakses property prototype
eko.sayBye(); // Good Bye
eko.run(); // Eko is running
budi.sayBye(); // Sampai jumpa
</script>
</body>
</html>