您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript原型继承和组合式继承代码实例详解

2024/5/14 15:54:58发布35次查看
原型(prototype):
function body(name,age){// 创建一个body类 this.name = name;// 赋予基础属性name、age this.age = age; } body.prototype.sayname =function() {// 给原型定义一个sayname的方法 console.log(this.name); } var a = new body('wutao','10');//创建一个body的实例对象 function another(){} another.prototype = new body('www');//将body实例对象给新创建的子类(another)的prototype属性,这样,another就拥有了body的属性和方法 var b = new another();//创建another子类的实例 another.prototype.sex ="mail";//定义子类的属性及方法 another.prototype.saysex = function(){ console.log(this.sex); } a.sayname();//wutao b.sayname();//www 实例b拥有父类body的方法sayname b.saysex();//mail 实例b拥有自己定义的方法saysex
借用构造函数(call&apply),也可以理解为组合式继承call:
function person(name){ this.name = name; this.sayhello = function(){ console.log(this.name); } } function son(name,age){ person.call(this,name,age);//call用法:将this指针指向父类构造函数,并依次传入参数,使其拥有父类的属性和方法 this.age = age; this.sayfunc = function(){ console.log(this.name+"-"+this.age); } } var a = new person('wutao'); var b = new son("wwwwww",22); a.sayhello();//wutao b.sayhello();//wwwwww; 通过call继承来的父类person的方法sayhello b.sayfunc();//wwwwww-22
apply:
function person(name){ this.name = name; this.sayhello = function(){ console.log(this.name); } } function son(name,age){ person.apply(this,[name,age]);//apply用法:类似call,将this指针指向父类构造函数,并传入一个由参数组成的数组参数,使其拥有父类的属性和方法 this.age = age; this.sayfunc = function(){ console.log(this.name+"-"+this.age); } } var a = new person('wutao'); var b = new son("ttt",222); a.sayhello();//wutao b.sayhello();//ttt;通过apply继承来的父类person的方法sayhello b.sayfunc();//ttt-222
js最主要的继承方法就这2种,当然,还有几种继承方法,但是有些继承方式在创建了实例之后,修改实例方法和属性会直接修改原型的方法和属性,那这样的继承就显得意义不大了,除非是业务有类似的需求才会去用到。
以上就是javascript原型继承和组合式继承代码实例详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product