JavaScript继承
JavaScript所谓继承就是从其他对象获取的属性和方法,子类继承父类。
在JavaScript中查找属性和方法:
1.先在自身查找
2.沿原型链向上查找
3.没有找到则返回undefined
JavaScript中的继承方式:
一、通过在子类中调用父类的方式,改变父类的执行环境:
function Father(){
this.name = 'father';
}
function Son(){
this.name = 'son';
// 调用父类
this.father = Father;
this.father();
}
二、通过原型链继承:
function Father(){
this.name = 'father';
this.fn = function(){
return this.name;
};
}
function Son(){
this.name = 'son';
}
Son.prototype = new Father(); // Son的原型是Father的实例
Object.defineProperty(Son.prototype,'constructor',{
value:'Son' // 修复constructor
});
这种继承方式只继承了父类的共有属性和方法,即原型上的方法。
三、通过修改this指向,获得其他对象的方法:
function Father(){
this.name = 'father';
}
function Son(){
this.name = 'son';
Father.call(this); // 修改this指向,并立即执行函数
// Father.apply(this);
// Father.bind(this)();
}
这种继承方式只继承了父类的私有属性和方法。
call()和apply()修改this指向后会立即执行函数,而bind()修改后返回新函数,不会立即执行。
四、混合继承:
基于上面二三两种继承方式,实现同时继承父类的共有和私有属性和方法。
function Father(){
this.name = 'father';
}
function Son(){
this.name = 'son';
Father.call(this); // 继承私有
}
Son.prototype = new Father(); // 继承共有
Object.defineProperty(Son.prototype,'constructor',{
value:'Son' // 修复constructor
});
五、class继承:
JavaScript中的class其实是原型的语法糖。
class Father{
constructor(){
this.name = 'father';
}
fn(){
console.log(this.name);
}
}
class Son extends A{} // 使用extends关键字
六、通过Object.create():
Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
function Father(){
this.name = 'father';
}
function Son(){
this.name = 'son';
Father.call(this); // 继承私有
}
Son.prototype = Object.create(Father.prototype); // 继承共有
// 相同的,使用Object.assign()
// Object.assign(Son.prototype,Father.prototype);
Object.defineProperty(Son.prototype,'constructor',{
value:'Son' // 修复constructor
});