68.tostring()

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <script type="text/javascript">
 7             
 8             function Person(name , age , gender){
 9                 this.name = name;
10                 this.age = age;
11                 this.gender = gender;
12             }
13             
14             //修改Person原型的toString
15             Person.prototype.toString = function(){
16                 return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]";
17             };
18             
19             
20             //创建一个Person实例
21             var per = new Person("孙悟空",18,"男");
22             var per2 = new Person("猪八戒",28,"男");
23             
24             //当我们直接在页面中打印一个对象时,事件上是输出的对象的toString()方法的返回值
25             //如果我们希望在输出对象时不输出[object Object],可以为对象添加一个toString()方法
26             //Person[name=孙悟空,age=18,gender=男]
27             /*per.toString = function(){
28                 return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]";
29             };*/
30             
31             var result = per.toString();
32             //console.log("result = " + result);
33             //console.log(per.__proto__.__proto__.hasOwnProperty("toString"));
34             console.log(per2);
35             console.log(per);
36             
37             
38         </script>
39     </head>
40     <body>
41     </body>
42 </html>

 

上一篇:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先


下一篇:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先