欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript中類的定義方式詳解(四種方式)

 更新時間:2015年12月22日 10:12:00   作者:釋然me  
這篇文章主要介紹了javascript中類的定義方式,結(jié)合實例形式較為詳細的分析了JavaScript中類的四種定義方式,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了javascript中類的定義方式。分享給大家供大家參考,具體如下:

類的定義包括四種方式:

1、工廠方式

function createCar(name,color,price){
  var tempcar=new Object;
  tempcar.name=name;
  tempcar.color=color;
  tempcar.price=price;
  tempcar.getName=function(){
   document.write(this.name+"-----"+this.color+"<br>");
  };
  return tempcar;
}
var car1=new createCar("工廠桑塔納","red","121313");
car1.getName();

定義了一個能創(chuàng)建并返回特定類型對象的工廠函數(shù), 看起來還是不錯的, 但有個小問題 ,

每次調(diào)用時都要創(chuàng)建新函數(shù) showColor,我們可以把它移到函數(shù)外面,

function getName(){
  document.write(this.name+"-----"+this.color+"<br>");
}

在工廠函數(shù)中直接指向它

復(fù)制代碼 代碼如下:
tempCar.getName = getName;

這樣避免了重復(fù)創(chuàng)建函數(shù)的問題,但看起來不像對象的方法了。

2、構(gòu)造函數(shù)方式

function Car(name,color,price){
  this.name=name;
  this.color=color;
  this.price=price;
  this.getColor=function(){
   document.write(this.name+"-----"+this.color+"<br>");
  };
}
var car2=new Car("構(gòu)造桑塔納","red","121313");
car2.getColor(); 

可以看到與第一中方式的差別,在構(gòu)造函數(shù)內(nèi)部無創(chuàng)建對象,而是使用 this 關(guān)鍵字。

使用 new 調(diào)用構(gòu)造函數(shù)時,先創(chuàng)建了一個對象,然后用 this 來訪問。

這種用法于其他面向?qū)ο笳Z言很相似了, 但這種方式和上一種有同一個問題, 就是重復(fù)創(chuàng)建函數(shù)。

3、原型方式

function proCar(){
}
proCar.prototype.name="原型";
proCar.prototype.color="blue";
proCar.prototype.price="10000";
proCar.prototype.getName=function(){
  document.write(this.name+"-----"+this.color+"<br>");
};
var car3=new proCar();
car3.getName();

首先定義了構(gòu)造函數(shù) Car,但無任何代碼,然后通過 prototype 添加屬性。優(yōu)點:

a. 所有實例存放的都是指向 showColor 的指針,解決了重復(fù)創(chuàng)建函數(shù)的問題

b. 可以用 instanceof 檢查對象類型

復(fù)制代碼 代碼如下:
alert(car3 instanceof proCar);//true

缺點,添加下面的代碼:

proCar.prototype.drivers = newArray("mike", "sue");
car3.drivers.push("matt");
alert(car3.drivers);//outputs "mike,sue,matt"
alert(car3.drivers);//outputs "mike,sue,matt"

drivers 是指向 Array 對象的指針,proCar 的兩個實例都指向同一個數(shù)組。

4、動態(tài)原型方式

function autoProCar(name,color,price){
  this.name=name;
  this.color=color;
  this.price=price;
  this.drives=new Array("mike","sue");
  if(typeof autoProCar.initialized== "undefined"){
   autoProCar.prototype.getName =function(){
   document.write(this.name+"-----"+this.color+"<br>");
   };
   autoProCar.initialized=true;
  }
}
var car4=new autoProCar("動態(tài)原型","yellow","1234565");
car4.getName();
car4.drives.push("newOne");
document.write(car4.drives);

這種方式是我最喜歡的, 所有的類定義都在一個函數(shù)中完成, 看起來非常像其他語言的類定義,不會重復(fù)創(chuàng)建函數(shù),還可以用 instanceof

希望本文所述對大家JavaScript程序設(shè)計有所幫助。

相關(guān)文章

最新評論