123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <script>
- function Person(name, age, gender) {
- this.name = name;
- this.age = age;
- this.gender = gender;
- }
-
- //修改Person原型的toString
- Person.prototype.toString = function () {
- return "Person[name=" + this.name + ",age=" + this.age + ",gender=" + this.gender + "]";
- };
- //创建一个Person实例
- var per = new Person("孙悟空", 28, "男");
- var per2 = new Person("二师兄", 38, "男");
- // 当我们直接在页面中打印一个对象时,实际上是输出对象的toString()方法的返回值
- // 如果我们希望在输出对象时不输出[onject Object],可以为对象添加一个toString()方法
- per.toString = function(){
- return "我是一个快乐的小Person";
- }
- per.toString = function(){
- return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]";
- };
- var result = per.toString();
- // console.log("result="+result);
- console.log(per);
- console.log(per2);
- console.log(per.hasOwnProperty("toString"));//输出结果为false
- console.log(per.__proto__.hasOwnProperty("toString"));//输出结果为false
- console.log(per.__proto__.__proto__.hasOwnProperty("toString"));//输出结果为true
- </script>
- </head>
- <body>
- </body>
- </html>
|