function GenericToString() {}//这是犀牛中的举例
GenericToString.prototype.toString = function() {
    var props = [];
    for(var name in this) {
        if (!this.hasOwnProperty(name)) continue;
        var value = this[name];
        var s = name + ":" 
        switch(typeof value) {
        case 'function':
            s += "function";
            break;
        case 'object':
            if (value instanceof Array) s += "array"
            else s += value.toString();
            break;
        default:
            s += String(value);
            break;
        }
        props.push(s);
    }
    return "{" + props.join(", ") + "}";
}
function Car(iColor, iDoors, iMpg){ 
        this.color = iColor; 
        this.doors = iDoors; 
        this.mpg = iMpg; 
        this.showColor = function(){ 
            alert(this.color); 
        }; 
    } 
Car.prototype=new GenericToString(); //这是我作验证的对象
var test=new Car(red,yingmen,wangwang);
test.toString()
//可是结果什么也没有,请教原因。

解决方案 »

  1.   

    function GenericToString() {}//这是犀牛中的举例
    GenericToString.prototype.toString = function() {
        var props = [];
        for(var name in this) {
            if (!this.hasOwnProperty(name)) continue;
            var value = this[name];
            var s = name + ":"
            switch(typeof value) {
            case 'function':
                s += "function";
                break;
            case 'object':
                if (value instanceof Array) s += "array"
                else s += value.toString();
                break;
            default:
                s += String(value);
                break;
            }
            props.push(s);
        }
        return "{" + props.join(", ") + "}";
    }
    function Car(iColor, iDoors, iMpg){
            this.color = iColor;
            this.doors = iDoors;
            this.mpg = iMpg;
            this.showColor = function(){
                alert(this.color);
            };
        }
    Car.prototype=new GenericToString(); //这是我作验证的对象
    var test=new Car("red","yingmen","wangwang");
    alert(test.toString());//可是结果什么也没有,请教原因。
      

  2.   

    {color:red,doors:yingmen,showColor:function}
    再次验证。以上为结果,没问题。
      

  3.   

    1楼的 法是对的:
    function Car(iColor, iDoors, iMpg){}中,有三个形式参数,用字符串写的,不用加引号
    new Car("red","yingmen","wangwang")中,输入三个实际参数,要加引号
    toString()中,把结果存在数组中,但是并没输出这个数组,所以想看到结果的话,还要document.write 或 alert