你是否遇到这样的疑惑?
代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script type="text/javascript">
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var one = new Person("草莓",10,"女");
var two = new Person("车厘子",20,"女");
console.log(one);
console.log(two);
</script>
</head>
<body>
</body>
</html>
输出结果是这样的:
其实这个输出的是该对象的toString()方法的返回值,你瞧:
那我要输出详细信息,我只要修改返回值呀:
因此我这样:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script type="text/javascript">
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var one = new Person("草莓",10,"女");
var two = new Person("车厘子",20,"女");
one.toString = function(){
return "姓名:" + this.name + ",年龄:" + this.age + ",性别:" + this.sex;
}
console.log(one);
console.log(two);
</script>
</head>
<body>
</body>
</html>
运行结果:
那我就修改上一级:
修改好了如下:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script type="text/javascript">
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var one = new Person("草莓",10,"女");
var two = new Person("车厘子",20,"女");
Person.prototype.toString = function(){
return "姓名:" + this.name + ",年龄:" + this.age + ",性别:" + this.sex;
}
console.log(one);
console.log(two);
</script>
</head>
<body>
</body>
</html>
运行结果: