一、对象冒充
Js代码 收藏代码
//对象冒充,是指将父类的属性和方法一起传给子类作为特权属性和特权方法
function Person(name,age){
this.name = name;
this.age = age;
this.sayHi = function(){
alert('hi');
}
}
Person.prototype.walk = function(){
alert('walk.......');
}
function Student(name,age,grade){
//是指将父类的属性和方法一起传给子类作为特权属性和特权方法。
this.newMethod = Person;
this.newMethod(name,age);
delete this.newMethod;//如果不删除,newMethod还有Person的prototype方法walk
this.grade = grade;
}
var s1 = new Student('xiaoming',10,3);
console.log(s1);//s1作为Student的对象,拥有父类和子类的属性
//Student { name="xiaoming", age=10, grade=3, sayHi=function() }
//s1.walk();//报错 s1.walk is not a function
//结论:Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。
二、call和apply(借用构造函数)
//使用call或apply改变对象的作用域来实现继承,让父类的this等于新创建的子类的对象
function Person(name,age){
this.name = name;
this.age = age;
this.sayHi = function(){
alert('hi');
}
}
Person.prototype.walk = function(){
alert('walk.......');
}
function Student(name,age,grade){
//让父类的this等于新创建的子类的对象
Person.call(this, name, age);
this.grade = grade;
}
var s1 = new Student('xiaoming',10,3);
console.log(s1);//s1作为Student的对象,拥有父类和子类的属性
//Student { name="xiaoming", age=10, grade=3, sayHi=function() }
//s1.walk();//s1.walk is not a function
//结论:同前面的对象冒充一样,Student类只继承了Person类的特权属性和方法,并没有继承Person类的共有属性和方法。