JavaScript 中的继承示例

javascriptweb developmentobject oriented programming更新于 2025/8/21 16:12:17

JavaScript 是一种基于原型的基于对象的语言。JavaScript 中的继承是使用原型对象实现的。

以下是在 JavaScript 中实现继承的代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18;
      color: blueviolet;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Inheritance</h1>
<div class="result"></div>
<button class="btn">点击此处</button>
<h3>
Click on the above button to call the welcome method inherited by person1 and person2 object
</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   function Person(name, age, city) {
      this.name = name;
      this.age = age;
      this.city = city;
   }
   Person.prototype.welcome = function () {
      resEle.innerHTML +=
      " Welcome "+this.name+" age: "+this.age +" city: "+this.city+"<br>";
   };
   BtnEle.addEventListener("click", () => {
      let person1 = new Person("Rohan", 22, "Delhi");
      person1.welcome();
      let person2 = new Person("Shawn", 19, "England");
      person2.welcome();
   });
</script>
</body>
</html>

输出

点击‘CLICK HERE’按钮 −


相关文章


有用资源