原型对象
为什么要使用原型对象?
通过构造函数创建对象的过程中,需要给对象添加方法,这些方法具有相同的代码,只是执行过程不同,但是却占用了不同的内存,也就浪费了内存,随着实例化次数的增加,浪费的内存也就会越来越多;如果将这些方法放在原型对象中,就可以起到共用一块内存的效果,也就是起到了节约内存的作用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Person(name,age){ this.name=name; this.age=age; this.say=function(){ alert(this.name); } } var p1=new Person("星爷",20); p1.say(); var p2=new Person("范爷",16); p2.say(); var p3=new Person("晨爷",18); p3.say(); console.log(p1.say==p2.say); console.log(p1.say.toString());
|
如何使用原型对象?
- 任何函数都会有一个prototype属性,该属性的值是一个对象,我们把它称之为原型对象。
- 给原型对象中添加的属性和方法都可以被构造函数的实例所共享。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| function Person(name,age){ this.name=name; this.age=age; } Person.prototype.say=function(){ alert(this.name); }; Person.prototype.run=function(){ alert("5公里越野"); }; var p1=new Person("冰冰",28); p1.say(); p1.run(); var p2=new Person("亮亮",10); p2.say(); p2.run(); console.log(p1.say==p2.say);
|
构造函数/原型/实例三者之间的联系
通过原型图可以很好的帮助我们理解三者之间的关联

再从代码上看看有什么关联吧
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Chinese(name){ this.name=name; } var lipi=new Chinese("里皮"); console.log(Chinese.prototype.constructor===Chinese); console.log(lipi.__proto__===Chinese.prototype); console.log(lipi.__proto__.constructor===Chinese); console.log(lipi.constructor===Chinese);
|
对象属性的查找
直接从代码上更直观的了解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function Student(){ this.name="小红"; } Student.prototype.say=function(){ }; var s1=new Student(); console.log(s1.name); console.log(s1.say); console.log(s1.toString); console.log(s1.say2); console.log(s1.__proto__.__proto__.__proto__);
|