03.toString.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script>
  9. function Person(name, age, gender) {
  10. this.name = name;
  11. this.age = age;
  12. this.gender = gender;
  13. }
  14. //修改Person原型的toString
  15. Person.prototype.toString = function () {
  16. return "Person[name=" + this.name + ",age=" + this.age + ",gender=" + this.gender + "]";
  17. };
  18. //创建一个Person实例
  19. var per = new Person("孙悟空", 28, "男");
  20. var per2 = new Person("二师兄", 38, "男");
  21. // 当我们直接在页面中打印一个对象时,实际上是输出对象的toString()方法的返回值
  22. // 如果我们希望在输出对象时不输出[onject Object],可以为对象添加一个toString()方法
  23. per.toString = function(){
  24. return "我是一个快乐的小Person";
  25. }
  26. per.toString = function(){
  27. return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]";
  28. };
  29. var result = per.toString();
  30. // console.log("result="+result);
  31. console.log(per);
  32. console.log(per2);
  33. console.log(per.hasOwnProperty("toString"));//输出结果为false
  34. console.log(per.__proto__.hasOwnProperty("toString"));//输出结果为false
  35. console.log(per.__proto__.__proto__.hasOwnProperty("toString"));//输出结果为true
  36. </script>
  37. </head>
  38. <body>
  39. </body>
  40. </html>