//JS中常用的几种继承 <script type="text/javascript"> //1.原型链实现继承 将父对象的属性和值依次赋给子元素 Object.prototype.ext=function(oParent){ //循环遍历父元素,将父元素的每一个属性和对应的值拷贝到子元素中 for(var i in oParent){ this[i]=oParent[i]; } } function Person(p_name,p_age){ this.name=p_name; this.age=p_age; this.sayHi=function(){ alert(this.name+","+this.age); }; } function Student(_sno){ this.sno=_sno; } var p1=new Person("ZDL",21); var p2=new Student('20132296'); p2.ext(new Person("知道了",21)); console.log(p1.name); //"ZDL" console.log(p2.name); //"知道了" p2.sayHi(); </script> ======================================== <script type="text/javascript"> //2.通过call和apply调用实现继承 function Person(p_name,p_age){ this.name=p_name; this.age=p_age; this.sayHi=function(){ alert(this.name+this.age); }; } function Student(p_name,p_age,_sno){ this.no=_sno; 通过函数的 call||apply 调用,将this改变成当前的这个对象, 从而实现了调用父类的够着函数为子类对象赋值 //Person.call(this,p_name,p_age); Person.apply(this,[p_name,p_age,_sno]); } var p2=new Student("找到了",21,"20132296"); p2.sayHi(); //找到了21 </script> <script type="text/javascript"> //3.通过原型对象实现继承 function Person(p_name,p_age){ this.name=p_name; this.age=p_age; } function Student(_sno){ this.sno=_sno; this.sayHi=function(){ alert(this.name+" ,"+this.age+", "+this.sno); }; } Student.prototype=new Person("钟小明",22); var p2=new Student("20132296"); p2.sayHi(); //钟小明 ,22, "20132296" var p3=new Student("20132298"); p3.sayHi();//钟小明 ,22, "20132298" //问题:原型对象的属性会被后面的所有子对象所共享,所以,我们只在里面定义一些所有对象共有的属性,相当于类的静态属性 </script>
转载请注明:副业 and 脱单研究所 » JS中常用的几种继承方式