现在的位置: 首页 > 综合 > 正文

Javascript面向对象编程——对象继承的写法

2012年02月19日 ⁄ 综合 ⁄ 共 2334字 ⁄ 字号 评论关闭

对象,具有属性与方法。这是大家都听到烂的话了。面向对象的基本特征有:封闭、继承、多态。今天来我总结一下我刚刚学到的,我只是把看到的冰山一角写下来了,希望可以完善。

     对象的继承相信大家都很熟悉了。可以用对象冒充、call()[apply()]、原型方式、混合方式这几种。其中混合方式我觉得是比较好的,先开回顾一下call()方法:

 

function useCall(a,b){
  this.a = a;
  this.b = b;
  this.say=function(){
    alert("I'm "+this.a+" You're"+this.b);
  }
 }
 function callThefunction (){
    var args = arguments;
    useCall.call(this,args[0],args[1]);
 //  useCall.apply(this,arguments);
  }
var testCall1 =new useCall("Not YY","Not TT");
testCall1.say();
var testCall2 = new callThefunction("YY","TT");
testCall2.say();

 

原型方式:

 

function car(price){
 this.price=price;
}
car.prototype={
    sayPrice:function(){console.log("Price is "+this.price);}  //console.log()参见Firebug API
}
function toyCar(price){
 this.price=price;
}
toyCar.prototype=new car()
var oCar=new car("100W");
oCar.sayPrice();
var oCar2=new toyCar("10CNY");
oCar2.sayPrice();

 

混合方式:

 

function house(size,price){
       this.size = size;
       this.price = price;
     }
     house.prototype.showArea=function (){
       console.log("面积为"+this.size);
     }
     house.prototype.sayPrice=function (){
       console.log("价钱为"+this.price);
     }
function maofan(size,price){
           house.call(this,size,price);
}
maofan.prototype=new house();

var newmaofan=new maofan("20Square meters ","1000CNY");
newmaofan.showArea();

 

混合方式另一种写法:

 

function house(size,price){
   this.size = size;
   this.price = price;
 }
 house.prototype={
          showArea:function(){
   console.log("面积为"+this.size);
 },       sayPrice:function(){
   console.log("价钱为"+this.price);
 }
}
function maofan(size,price){
          house.call(this,size,price);
}
maofan.prototype=new house();
var newmaofan=new maofan("20 Square meters ","1000CNY");
newmaofan.showArea();
newmaofan.sayPrice();

 

 为继承的对象追加一个方法试试:

 

function house(size,price){
   this.size = size;
   this.price = price;
 }
 house.prototype={
          showArea:function(){
   console.log("面积为"+this.size);
 },       sayPrice:function(){
   console.log("价钱为"+this.price);
 }
}
function maofan(size,price){
          house.call(this,size,price);
}
maofan.prototype=new house();
maofan.prototype.Sayid=function(id){ //在继承了之后再添加方法,不然就出错了,找不到方法
   this.id = id;
   console.log("ID is:"+this.id);
}
var newmaofan=new maofan();
newmaofan.Sayid("888");//Output ID:888

 

     几个例子,都可以去试一下。我从来没想过高手会看这些文章,只是写之前刚入门的。所以要是写的不好就不要见怪了。这些Demo只要试过了,加上你查的资料应该对这个JavaScript继承这一块就熟悉了。值得说的是,有很多的写法,我们新手是没见过的。像混合方式的另一种写法,我是不经常这样用。在我看来就是一个数组,这样理解会好很多。例子看多了,看难的例子就不会晕。不过我看到长的还是会晕,还会出现_string_这种,虽然没什么了不起,看得心里不明白就不想看下去了。所以,要学真功夫还是没这么简单的。

     还忘了一点,在写call()的时候,我一开始是这样写的:xxx.call(this,a,b);但是这样却报错了。为什么呢?这里要谢谢JS群里的司马闲大哥,call(thisobj,args[0]…)。如果像我那样写,不仅是参数不对,还有就是根本乱用参数。

抱歉!评论已关闭.