文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Javascript面向对象编程——对象继承的写法

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

时间:2010-09-25  来源:酷冰者

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

     对象的继承相信大家都很熟悉了。可以用对象冒充、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();

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

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

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载