首页 > 代码库 > 继承性—javascript面向对象高级
继承性—javascript面向对象高级
## 继承性 ##
js不是一门完全是面向对象的语言,它没有专门实现对象继承的机制,但是可以通过语法层面实现对象的继承,要实现继承可以通过以下几种方式实现继承。
(这里也可以通过ES6中的class语法实现继承,更接近传统语言如java,请见我ES6新特性)
2.通过constructor实现传值。
3.类Class的概念:构造函数
通过构造函数产生的对象叫做实例。具备构造函数的所有属性
将公用的方法和属性,提取出来存到原型上
继承的几种方式
1.通过原型实现继承
function Father(){
this.name = ‘zhangsan‘;
this.age = 12;
this.gender = ‘mail‘;
this.sayHello = function(){
console.log(‘hello,i m ‘+this.name +‘,i m ‘+this.age+‘years old‘)
}
}
function Child(){};
Child.prototype = new Father();
var c1 = new Child();
c1.sayHello()
2.传参数的原型式继承
function Father(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
//定义父对象
Father.prototype.sayHello = function(){
console.log(‘hello,i m ‘+this.name +‘,i m ‘+this.age+‘years old‘)
}
function Child(name,age,gender){
this.constructor(name,age,gender)
// 将参数传给constructor
};
Child.prototype = new Father();
var c1 = new Child(‘zhangsan‘,40,‘femail‘);
c1.sayHello()
**存在的问题:该方法是采用的原型覆盖的方法,会继承父元素的所有属性,但是如果父元素不具备某些子元素特有的原型属性的话。就会丢失该属性。**
3.对象冒充
将某一个构造函数当做普通函数调用,执行后会生成指向当前对象
function Father(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
Father.prototype.sayHello = function(){
console.log(‘hello,i m ‘+this.name +‘,i m ‘+this.age+‘years old‘)
}
function Child(name,age,gender){
this.newObj = Father;//这句话是重点
this.newObj(name,age,gender)
//这里将Father函数当成一个普通函数,执行后会产生一个对象,着就是对象冒充
delete this.newObj
};
var c1 = new Child(‘lis‘,40,‘femail‘);
console.log(c1.name)
**问题:该方式不能继承Father原型上的属性。 **
4.通过call和apply手动改变this的指向,原理:(对象冒充)
function Father(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
Father.prototype.sayHello = function(){
console.log(‘hello,i m ‘+this.name +‘,i m ‘+this.age+‘years old‘)
}
function Child(name,age,gender){
Father.call(this,name,age,gender)
//这句话是关键,将Father里的所有this都指向Child
};
var c1 = new Child(‘zhangsan‘,40,‘femail‘);
c1.sayHello()
** 问题:因为实质是对象冒充,所以也不能继承Father的原型**
5.组合式继承(混合)
function Father(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
Father.prototype.sayHello = function(){
console.log(‘hello,i m ‘+this.name +‘,i m ‘+this.age+‘years old‘)
}
function Child(name,age,gender){
Father.call(this,name,age,gender)
};
//这里不仅用对象冒充用了Father这个构造函数,
//还继承了Father的prototype
Child.prototype = Father.prototype;
var c1 = new Child(‘lis‘,40,‘femail‘);
console.log(c1)
c1.sayHello()
继承性—javascript面向对象高级