6.prototype属性

来源:互联网 发布:淘宝衣服检测 编辑:程序博客网 时间:2024/06/05 12:43

首先我们需要了解prototype到底是什么呢?

执行下一段代码

            function Person(){              this.name = "";              this.age = 0;            }            Person.prototype.count = 1;

这里写图片描述

在这里我们会发现Person.prototype指向的对象他的construct指回他本身(注意只有函数对象有prototype属性)

这里写图片描述

我们可以利用prototype属性做什么呢?设置公有属性

            function Person(){              this.name = "";              this.age = 0;            }            Person.prototype.count = 1;            var p1 = new Person();            var p2 = new Person();            console.log(p1.count);//Output 1            console.log(p2.count);//Output 1            Person.prototype.count = 2;            console.log(p1.count);//Output 2            console.log(p2.count);//Output 2

这里写图片描述

所有的对象都使用着count这一个空间,类似于C++中静态变量这一概念,而p1.count与Person.prototype.count不同,当你对于p1.count进行赋值时,它相当于对于p1这个对象添加一个count属性,然后将这个属性的值赋值给这个成员的count属性而不是Person.prototype.count。当你用delete方法删除一个对象属性时再输出,那么他的prototype属性值将会重新暴露出来

            var p1 = new Person();            var p2 = new Person();            p1.count = 2;            console.log(p1.count);//Output 2            console.log(p2.count);//Output 1            delete p1.count;            console.log(p1.count);//Output 1
原创粉丝点击