日期:2014-05-16  浏览次数:20399 次

关于原型的一点点问题

function people(a,b,c){
        this.name = a;
        this.age = b;
        this.sex = c;
        this.toString = function(){
                return this.name + this.age + this + sex;
        }
}

这是第一种方法。

function people(a,b,c){
        this.name = a;
        this.age = b;
        this.sex = c;
}
people.prototype.toString=function(){ return this.name + this.age + this + sex; }

这是第二种。

tostring这个方法是每个使用people构造器分别重新定义的,不太理解这句话的意思。
------解决方案--------------------
这个应该是说,你这里的代码中,toString方法是自定义的。
因为toString方法是属于Object对象中的一个基本方法,所有继承自Object对象的对象,都会继承toString方法。

如果新对象自己重写了toString方法,那么重写的新方法,就会覆盖掉继承来的方法。

这样举个简单的例子:

function people(a,b,c){
    this.name = a;
    this.age = b;
    this.sex = c;
}
var a = new people(1,2,3);
console.log(a.toString());
//使用的Object中的toString方法

function people1(a,b,c){
    this.name = a;
    this.age = b;
    this.sex = c;
this.toString = function(){
        return this.name + this.age + this.sex;
    }
}
var b = new people1(4,5,6);
console.log(b.toString());
//使用的自己重现定义的新方法


PS:你代码中的取值写错了哦
return this.name + this.age + this + sex;

第三个取值,如果按你这样写,会报错的