原型继承、构造函数继承、组合继承法

6次阅读

共计 1799 个字符,预计需要花费 5 分钟才能阅读完成。

原型继承

function Person(name,sex){
this.name=name;
this.sex=sex;
this.friends = {lily:’female’,lucy:’female’};
this.showFriends=function(){
var str = ”
for(i in this.friends){
str+=i +’ ‘+this.friends[i] +’,’;
}
console.log(‘my friends:’+str);
}
}
Person.prototype.hello=function(){
console.log(‘hello:’+this.name);
}

var per1 = new Person(‘A’,’male’);
per1.hello();
per1.showFriends();

function Student(className){
this.class = className;
}

Student.prototype = new Person(‘B’,’male’);// 原型继承将子对象的原型对象指向父对象的实例;缺点:不能由子对象像父对象传递参数,

var stu1 = new Student(1);// 不能由子对象像父对象传递参数,
stu1.name=’C’;
stu1.hello();
stu1.friends.C = ‘male’;//2、对于引用型的属性修改之后会印象其他的实例对象;
stu1.showFriends();//2、对于引用型的属性修改之后会印象其他的实例对象;

console.log(“stu1 instanceof Student: “);
console.log(stu1 instanceof Student);
console.log(“stu1 instanceof Person: “);
console.log(stu1 instanceof Person);

var stu2 = new Student(2);
stu2.name=’D’;
stu2.hello();
stu2.showFriends();//2、对于引用型的属性修改之后会印象其他的实例对象;

console.log(“stu2 instanceof Student: “);
console.log(stu2 instanceof Student);
console.log(“stu2 instanceof Person: “);
console.log(stu2 instanceof Person);

缺点:1、不能由子对象像父对象传递参数,2、对于引用型的属性修改之后会印象其他的实例对象;
构造函数继承
// 构造函数继承
function Teacher(name,sex,type){
this.type=type;
Person.call(this,name,sex);
}

var tea1 = new Teacher(‘E’,’female’,’ 数学 ’);
//tea1.hello(); // 报错没有继承到原型上的方法
tea1.friends.F = ‘male’;
tea1.showFriends();

var tea2 = new Teacher(‘G’,’male’,’ 语文 ’);
tea2.friends.H = ‘male’;
tea2.showFriends();
console.log(“tea2 instanceof Teacher: “)
console.log(tea2 instanceof Teacher);
console.log(“tea2 instanceof Person: “)
console.log(tea2 instanceof Person);

缺点:1、不能继承父对象原型上的方法 2、每次实例化对象会重新构建函数,浪费内存。
组合继承法
把父对象方法挂载到父类的原型对象上去,实现方法复用
function Worker(name,sex,job){
this.job = job;
Person.call(this,name,sex)
}
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;// 原型的构造函数指向 worker

var wor1 = new Worker(‘I’,’female’,’ 程序员 ’);
wor1.hello();
wor1.friends.J = ‘male’;
wor1.showFriends();

正文完
 0