<script type="text/javascript">
function CreateCar(color,doors,speed){
var TemCar = new Object;
this.color = color ;
this.doors = doors ;
this.speed = speed;

  TemCar.Showcolor =  function(){
alert(this.color);
}

return TemCar;
}
var NewCar = CreateCar("red",4,133);
NewCar.Showcolor(); </script>
为什么执行后 alert 提示框是undefined

解决方案 »

  1.   

    TemCar.Showcolor = function(){
    alert(this.color);
    }
    这里的this是指TemCar跟上面没有关系
      

  2.   


    <script type="text/javascript">//可以用两种方法实现上面的例子
    //第一种 js对象的prototype属性  对象的新实例会"继承"赋予该对象原型的操作,也就是可以使用js对象prototype属性为对象增加方法
    function CreateCar(color,doors,speed){
    this.color = color;
    this.doors = doors;
    this.speed = speed;
    }  CreateCar.prototype.ShowColor = function (){   //为对象增加原形方法
     alert(this.color);
    } var NewCar = new CreateCar("red",4,133);
    NewCar.ShowColor();

    </script><script type="text/javascript">
    //另一种方法,也可以实现同样的功能,而且更好的理解 function CreateCar(color,doors,speed){

    this.color = color ;
    this.doors = doors ;
    this.speed = speed; this.Showcolor = showColor;  //为属性增加一个方法 function showColor(){
    alert(this.color);
    }
    } var NewCar = new CreateCar("red",4,133);
    NewCar.Showcolor();  //调用类中的方法
    </script>
      

  3.   

    因为你创建的新对象没有showColor这个方法!所以是undefined。
    至于为什么?是因为你的构造函数里面的showColor方法是定位为一个内部对象!
      

  4.   

    this的用法,应该是执行哪个函数的时候,这个this就是指向哪个函数那么,function CreateCar(color,doors,speed){
    var TemCar = new Object;
    this.color = color ;//这里的this是指向CreateCar,和TemCar 毫无关系
    this.doors = doors ;//同上
    this.speed = speed;//同上TemCar.Showcolor = function(){
    alert(this.color);;//这里的this是指向TemCar.Showcolor,你又没有给这个属性定义值,当然是undefined
    }return TemCar;
    }小弟也是刚学,如果说的不对,还的指正,谢谢
      

  5.   

    function CreateCar(color,doors,speed){
    var TemCar = new Object;
    this.color = color ;
    this.doors = doors ;
    this.speed = speed;TemCar.Showcolor = function(){
    alert(this.color);
    }return TemCar;//函数返回值,请注意,该对象一个成员都没有添加
    }
    var NewCar = CreateCar("red",4,133);//直接调用函数,获得函数返回值,没有添加成员的对象
    NewCar.Showcolor();这儿CreateCar没有被当作构造函数使用,获得的是函数返回值,是一个new Object(),明白了么?
    改一下:var NewCar =new CreateCar("red",4,133);//用函数构造成员,函数内添加有几个属性
    NewCar.Showcolor();//有了
      

  6.   

    this指针的问题!嗯,大家说的都对!
      

  7.   

    function CreateCar(color,doors,speed){
    var TemCar = new Object;
    this.color = color ;//这里的this是指向CreateCar,和TemCar 毫无关系
    this.doors = doors ;//同上
    this.speed = speed;//同上TemCar.Showcolor = function(){
    alert(this.color);;//这里的this是指向TemCar.Showcolor,你又没有给这个属性定义值,当然是undefined
    }return TemCar;
    }
      

  8.   


    不要搞錯了,this是指向window的