JavaScript 对象特性(任务)

任务

1.任务介绍

定义一个Student类作为Person类的子类,在Student类中继承父类的walk()方法、重新定义父类的sayHello()方法并添加Student类自己的sayGoodBye()方法。

2.任务目标

理解JavaScript面向对象的四大特性并掌握创建对象的方法。

3.实现思路

(1)选用构造函数模式创建对象,并且将属性为方法的属性定义到属性之外。

(2)全局变量是绑定在window对象上的,是window对象的属性。

<html>

  <head>
    <title>类的特性案例</title>
  </head>
    <body>
    <script type="text/javascript">
    function Person(firstName)
    {
    this.firstName = firstName;
    }
    Person.prototype.walk = function()
    {
    console.log("I'm walking");
    }
    Person.prototype.sayHello = function()
    {
    console.log("Hello,I am"+this.firstName);
    }
    function Student(firstName,Subject)
    {
    Person.call(this,firstName);
    this.Subject=Subject;
    }
    Student.prototype = Object.create(Person.prototype);
    Student.prototype.sayHello = function()
    {
    console.log("Hello,I am"+this.firstName+",I am Student"+this.Subject);
    }
    Student.prototype.sayGoodBye = function()
    {
    console.log("goodbye");
    }
    var s = new Student("带土","数学");
    s.walk();
    s.sayHello();
    s.sayGoodBye();
    console.log(s instanceof Person);
    console.log(s instanceof Student);
    </script>
  </body>
</html>

这样Student拥有了3个方法,一个是完全从父类那里来的walk方法;第二个sayHello方法是父类也有,Student方法也有,但是重写了出,就调用自己的;第三个是Student自己所独有的方法。

我们可以通过instanceof来判断一个对象是不是类的实例。

运行结果如下:

 

原文地址:https://www.cnblogs.com/daitu/p/javascript.html