As an object-oriented language, inheritance is naturally a major feature. The following is a very simple code example, which demonstrates the basic principles of inheritance. Friends who are interested or want to learn this aspect can refer to it. , I hope I can help everyone.
//继承 function Person(name,sex) { this.name=name; this.sex=sex; } Person.prototype.sayName=function() { alert(this.name); } Person.prototype.saySex=function() { alert(this.sex); } function Worker(name,sex,job) { //继承person类 Person.call(this,name,sex) //这里的this指的是Worker类的实例,如下面的'W' ,把W传入Person构造函数,这时W伪装成Person构造函数里的this this.job=job; } //Worker.prototype=Person.prototype;//如果这样负值原型,子类的sayJob方法Person父类也会有sayJob方法,因为是引用传递 //改成如下方式则子类不会影响父类: for(var i in Person.prototype) { Worker.prototype[i]=Person.prototype[i]; } Worker.prototype.sayJob=function() { alert(this.job); } var p=new Person('lisi','男'); //alert(p.sayJob); var w=new Worker('zhangsan','男','打酱油的'); w.sayName(); w.saySex(); w.sayJob();
The above is the entire content of this article, I hope you all like it.