function car (sColor,iNumbers){ // 構(gòu)造函數(shù)只用來定義對象的所有非函數(shù)屬性,即對象的屬性 this.color = sColor; this.numbers = iNumbers; this.dirvers = new Array ("Jone","Leon"); } car.prototype.showColor = function (){ // 原型方式只用來定義對象的所有函數(shù)屬性,即對象的方法 alert(this.color); } var car1 = new car("red"); var car2 = new car("yellow"); car1.showColor)(); car2.showColor)();
function car (sColor,iNumbers){ // 構(gòu)造函數(shù)只用來定義對象的所有非函數(shù)屬性,即對象的屬性 this.color = sColor; this.numbers = iNumbers; this.dirvers = new Array ("Jone","Leon"); if(typeof car._initialized=="undefined"){ //此時此刻,這里的car._initialized成立,繼續(xù)執(zhí)行下面的函數(shù) car.prototype.showColor = function (){ alert(this.color); } } car._initialized = true; // 執(zhí)行到這里就停止再也不在執(zhí)行第二次,因為此時此刻,car._initialized只是函數(shù)的屬性,而不是函數(shù)對象的原型屬性,如果是原型屬性的話,new一個函數(shù)對象的實例,就會改變函數(shù)里面原型對象的屬性,那么就會重復構(gòu)造showColor這個函數(shù)。正因為是這個原因,當car._initialized等于undefined的時候,執(zhí)行一次showColor,最后得到的car._initialized=true,這個時候改變的是函數(shù)的屬性,而不是函數(shù)原型的屬性,所以外部new一個對象實例根本無法改變函數(shù)的屬性,所有紅色部分的代碼就是為了做一件事情:只執(zhí)行紅色代碼之間的方法,并且每種方法只有一次,不會重復執(zhí)行! } var car1 = new car ("red"); var car2 = new car ("yellow"); car1.showColor(); car2.showColor();