1 .__proto__关键字(找个原型对象)

用关键字,给对象找个父类,这个父类叫原型对象。然后对象就有了原型对象的属性和方法。

而且可以在代码种,改变原型对象。

完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript学习</title>
<script>
'use strict';
var Student = {
name: "WangZan",
age: 25,
run: function () {
console.log(this.name + " run...");
}
};

var xiaoming = {
name: "xiaoming"
};

xiaoming.__proto__ = Student;
console.log(xiaoming.run());

var Bird = {

fly: function () {
console.log(this.name + " fly...");
}
};

xiaoming.__proto__ = Bird;
console.log(xiaoming.fly());

</script>
</head>
<body>
</body>
</html>

JavaScript的面向对象编程

2 class继承(推荐用这个,比上面的原型继承要好)

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>JavaScript学习</title>
   <script>
       'use strict';
       class Student{
          constructor(name) {
              this.name = name;
          }
           hello () {
               alert(this.name);
          }
      }

       class xiaoStudent extends Student {
           constructor(name,grade) {
               super(name);
               this.grade = grade;
          }
           hello_2 () {
               alert(this.name + this.grade);
          }
      }

       var xiaoming = new Student("xiaoming");
       xiaoming.hello();    //输出:xiaoming
       var xiaoming = new xiaoStudent("WangZan",1);
       xiaoming.hello_2();  //输出:WangZan1

   </script>
</head>
<body>
</body>
</html>

 

相关文章:

  • 2021-07-06
  • 2021-08-12
  • 2021-06-28
猜你喜欢
  • 2022-01-29
  • 2021-09-17
  • 2021-11-08
  • 2021-10-29
相关资源
相似解决方案