javascript 面向对象写法

本文深入探讨了JavaScript中常见的几种继承方式,包括原型继承、构造函数继承、call和apply方法实继承,以及如何整合使用这些方法。通过具体案例解析,帮助开发者理解不同继承方式的原理及适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//原型方法
function ClassA(){

}
ClassA.prototype = {
color:'red',
sayColor:  function (){
alert(this.color);
}
}

function ClassB(){
this.name = "";
this.sayName = function(){
alert(this.name);
}
}
ClassB.prototype = new ClassA();

var objA = new ClassA();
var objB = new ClassB();


objA.color = 'red';
objB.color = 'blue';

objB.name = 'caibinghong';

objA.sayColor();
objB.sayColor();// b类通过原型的方法 继承  A 类
objB.sayName();


//对象冒充  方法实继承
function person(){
this.name = 'person';
this.getName = function(){
alert(this.name);
}
}
function worker(name,age){
//对象冒充继承
this.constructor = person;
this.constructor(name);
delete this.constructor;

this.name = name||'caibinghong';
this.age = age||'2012';
this.getAge = function(){
alert(this.age);
}
}


var man = new person();
var xiaofan = new worker('xiaofan',28);


man.getName();
xiaofan.getName();
xiaofan.getAge();


// call 方法实继承


 var ClassC = function(sColor,tt){
this.color = sColor;
this.tt = tt;
this.sayColor = function (){
alert(this.color+this.tt);
}
}
var ClassD = function(sColor,sName){
ClassC.call(this,sColor,sName);//call 方法继承 传参 只能 以逗号隔开

this.name = sName;
this.sayName = function(){
alert(this.name);
}
}


var objC = new ClassC('___red','_cc : call  方法 传参 只能 以逗号隔开');
var objD = new ClassD('___blue','___D_caibinghong : call  方法 传参 只能 以逗号隔开');


objC.sayColor();
objD.sayColor();
objD.sayName();


// apply 方法实继承


 var ClassE = function(sColor,tt){
this.color = sColor;
this.tt = tt;
this.sayColor = function (){
alert(this.color+this.tt);
}
}
var ClassF = function(sColor,sName){
ClassE.apply(this,[sColor,sName]);//apply 方法继承 传参 只能数组

this.name = sName;
this.sayName = function(){
alert(this.name);
}
}


var objE = new ClassC('___red','____ee : apply  方法 传参 只能数组');
var objF = new ClassD('___blue','___F_caibinghong : apply  方法 传参 只能数组');


objE.sayColor();
objF.sayColor();
objF.sayName();




//根据上面的几种方法,下面来整合一下.
var  fdauto = function (age){ 
this.age = age;

fdauto.prototype = { 
getAge:function (){
alert(this.age);
}
}
var fdAm = function (age,name){
fdauto.call(this,age);//构造??
this.name = name;
}


fdAm.prototype = new fdauto();//继承??  这里有点不是很明白
fdAm.prototype.getName=function (){
alert(this.name);
};




var _fdauto = new fdauto(12);
var _fdAm = new fdAm(10,'the am of fdauto!!');


_fdauto.getAge();
_fdAm.getAge();

_fdAm.getName();

 

 

91百色都市

91环球网

91时尚资讯

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值