码迷,mamicode.com
首页 > Web开发 > 详细

JS中“类”继承和原型继承

时间:2015-09-02 23:18:25      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

类继承:

    先用函数构造器创建了一个“类”Student,然后在Student原型上定义了一个方法sayHello,然后创建了一个"类“PrimaryStudent,用apply()初始化PrimaryStudent。

然后让PrimaryStudent的原型等于Student创建的对象,并把PrimaryStudent原型上的构造器指向当前”类“,即PrimaryStudent,注意红色加粗部分。

 1 function Student(name){
 2     this.name = name;
 3 }
 4 Student.prototype.sayHello = function(){
 5     console.log(this.name);
 6 }
 7 function PrimaryStudent(name){
 8     Student.apply(this,arguments);
 9 }
10 PrimaryStudent.prototype = new Student();
11 PrimaryStudent.prototype.constructor = PrimaryStudent;
12 var stu = new PrimaryStudent("yxz");
13 stu.sayHello(); //输出yxz

原型继承:

原型继承和”类“继承关键的不同地方在于下面红色加粗部分,这里先定义了一个空的函数F,然后将Student的原型prototype赋值给F的原型prototype,然后再

执行PrimaryStudent.prototype = new F()。
 1 function Student(name){
 2     this.name = name;
 3 }
 4 Student.prototype.sayHello = function(){
 5     console.log(this.name);
 6 }
 7 var F = function(){
 8 
 9 }
10 function PrimaryStudent(name){
11     Student.apply(this,arguments);
12 }
13 F.prototype = Student.prototype;
14 PrimaryStudent.prototype = new F();
15 PrimaryStudent.prototype.constructor = PrimaryStudent;
16 var stu = new PrimaryStudent("yxz");
17 stu.sayHello();

JS中“类”继承和原型继承

标签:

原文地址:http://www.cnblogs.com/yxz-turing/p/4779570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!