看代码:
function createCar(sColor,iDoors,iMpg){
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
this.showColor=function(){
alert(this.color)
}
}
var carI=new createCar("red",4,23);
var carII=new createCar("blue",3,25);
alert(carI.showColor==carII.showColor)//结果为false上面代码alert出来是false,是因为每个实例都有自己独立的showColor,但是这其中的来龙去脉是什么?把上述代码改为
function createCar(sColor,iDoors,iMpg){
this.color=sColor;
this.doors=iDoors;
this.mpg=iMpg;
this.showColor=shoColor
}
function showColor(){
alert(this.color)
}
var carI=new createCar("red",4,23);
var carII=new createCar("blue",3,25);
alert(carI.showColor==carII.showColor)alert出来的结果是true,为什么呢?

解决方案 »

  1.   

    =showColor
      

  2.   

    你第二个 showColor函数是全局的   各对象中的变量都指向他的 所以当然相等
      

  3.   


    function createCar(sColor,iDoors,iMpg){
        this.color=sColor;
        this.doors=iDoors;
        this.mpg=iMpg;
      
    }
    createCar.prototype.showColor=function (){
    alert(this.color)
    }var carI=new createCar("red",4,23);
    var carII=new createCar("blue",3,25);
    alert(carI.showColor==carII.showColor)这样也是TRUE!原理思路同2#,大家共同的函数,建多少个对象都不会重构这个函数!