JavaScript原型链继承的对比

来源:互联网 发布:淘宝网 欧瑞斯的价格 编辑:程序博客网 时间:2024/06/05 04:44

1、代码

function Person(name, age) {this.name = name;this.age = age;}Person.prototype.sayHello = function() {console.log("My name is " + this.name + ", and age is " + this.age);}function Student() {}

2、通过Student.prototype = Person.prototype 的继承方式

      2.1  继承的实现

             1. 代码

Student.prototype = Person.prototype;var studentA = new Student();

             2. 结果查看

                

       2.2  缺点:在子类的原型里面,添加的方法和属性,父类对象也可以访问到

              

3、通过 Student.prototype = new Person() 的继承方式

   3.1  继承的实现

             1. 代码

Student.prototype = new Person();var studentA = new Student();

             2. 结果的查看

             

   3.2  缺点:在子类的 对象里面,会拥有父类中非原型的属性(例如age,name属性)

          

4、通过C.prototype = Object.create(Person.prototype)的继承方式

       4.1.继承的实现

             1. 代码

Student.prototype = Object.create(Person.prototype);var studentA = new Student();
            2. 结果的查看

                 

       4.2.缺点(完美)  

       4.3 Object.create()的内部实现

function create(clazz) {function F() {};F.prototype = clazz;var _protoType = new F();return _protoType;}

5、constructor修正问题(Student.prototype.constructor = Student;)

     

Student.prototype = Object.create(Person.prototype);Student.prototype.constructor = Student;

6、完整的参考代码

<script>function create(clazz) {function F() {};F.prototype = clazz;var _protoType = new F();return _protoType;}function Person(name, age) {this.name = name;this.age = age;}Person.prototype.sayHello = function() {console.log("My name is " + this.name + ", and age is " + this.age);}function Student() {}//通过原型链的方式,完成方法的继承//Student.prototype = Person.prototype;//Student.prototype = new Person();Student.prototype = Object.create(Person.prototype);var studentA = new Student();</script>



1 0
原创粉丝点击