javascript原型和继承的写法总结
2026-05-02 21:48:07
241
分类:javascript归档
原型的写法
现在有一个"动物"对象的构造函数
function Animal(){
}它的原型写法可以为
Animal.prototype.species = '动物';
Animal.prototype.action = function () {
}也可以是这样,但是这种写法需要手动设置它的constructor,否则cat1.constructor将丢失。
Animal.prototype={
constructor:Animal,
species:'动物',
action:function () {
}
}
var cat1=new Animal();
console.log(cat1.constructor==Animal); // true还可以用Object.assign(),这是ES5的属性,老版本的浏览器可能不支持。
Object.assign(Animal.prototype,{
constructor:Animal,
species:'动物',
action:function () {
}
});还可以用class,这是ES6的语法糖写法。这种写法代码的可读性变得更高。
class Animal {
constructor() {
this.species = '动物';
}
action() {
}
}原型的继承
1.构造函数绑定
第一种方法也是最简单的方法,使用call或apply方法,将父对象的构造函数绑定在子对象上,即在子对象构造函数中加一行
function Cat(name, color) {
Animal.call(this);
//Animal.apply(this, arguments);
this.name = name;
this.color = color;
}2.prototype模式
Cat.prototype = new Animal(); Cat.prototype.constructor = Cat;
3.ES6语法糖extends
class Cat extends Animal {
constructor(name, color) {
super();
this.name = name;
this.color = color;
}
action() {
console.log('捉老鼠')
}
}注:前面两种继承方法只能继承构造函数,而不能继承构造函数的原型,要完全继承构造函数和它的原型需要这样
Cat.prototype = Object.assign(Object.create(Animal.prototype), {
constructor:Cat,
});使用语法糖class也有它的弊端:不够灵活。比如要写个私有变量、写个闭包,完全用class的方式不能实现。