Home >Web Front-end >JS Tutorial >Four Steps to JS Prototype Inheritance
Inheritance is actually an extension of type. However, since JavaScript adopts prototypal inheritance, the editor below will share with you an article on the four steps of JS prototypal inheritance and an overview of the prototypal inheritance diagram, which has a good reference value. I hope to be helpful.
1: Four steps of js prototype inheritance
##
//js模拟类的创建以及继承 //动物(Animal),有头这个属性,eat方法 //名字这个属性 //猫有名字属性,继承Animal,抓老鼠方法 //第一步:创建父类 function Animal(name){ this.name = name; } //给父类添加属性方法 Animal.prototype.eat = function(){ console.log(this.name + " eating..."); } //第二步:创建子类 function Cat(name){ Animal.call(this,name); } //第三步:确定继承的关系 Cat.prototype = Object.create(Animal.prototype); //第四步:改造构造器 //改变了某个构造器的原型之后,紧接着的代码一定是改构造器 Cat.prototype.constructor = Cat; Cat.prototype.zhualaoshu = function(){ console.log(this.name + " 抓 老鼠"); } var mao = new Cat("猫"); mao.eat(); mao.zhualaoshu();
Two: Prototype inheritance diagram
Practice to consolidate understanding,
No | |
It cannot | |
Function() | |
Object.prototype | |
Method | |
Yes, it is Function.prototype; | |
Wrong | |
Create a parent class——>Create a subclass——>Determine the inheritance relationship——>Change the constructor | |
Can | |
Wrong | |
wrong |
#related suggestion:
The above is the detailed content of Four Steps to JS Prototype Inheritance. For more information, please follow other related articles on the PHP Chinese website!