|
|
谢谢大家观看我的博客,接下来讲讲javascript prototype相关的内容,本人知识有限,希望有误的地方请多多指教!
prototype可以概括为几句:
prototype相当于java对象中的一个静态属性,所以每个新生成的对象都共有这个prototype属性,如果对prototype做相应的修改,新生对象--地址引用的属性(比如Array,{})都会有影响,而对于值引用的属性不会有影响(比如String,int).
实例:
function ClassA(){ }function Pro(){this.p1 = 'p1';this.fun1 = function(){console.log('fun1');};this.arr = [];}var pro = new Pro()ClassA.prototype = pro;var a1 = new ClassA();var a2 = new ClassA();//a1,a2共享prototype(pro)属性a1.p1 = 'a1p1';console.log('a1.p1='+a1.p1+'| a2.p1='+a2.p1);//这里是值引用所以a1.p1的改变不会影响a2.p1a1.arr.push(1,2,3);console.log('a1.arr='+a1.arr+'| a2.arr='+a2.arr);//这里是地址引用,所以a1.arr的改变会影响a2.arr
关于constructor,我有两句话要说:1、constructor属性始终指向创建当前对象的构造函数。 2、每个函数都有一个默认的属相prototype,而这个prototype的constructor指向该函数。
//constructor属性始终指向创建当前对象的构造函数//---每个函数都有一个默认的属性prototype,而这个prototype的constructor指向这个函数console.log('--Example_One--');var Person = function(name){this.name = name;};Person.prototype.getName = function(){return this.name;}var p = new Person('zhang');console.log(Person.constructor === Function); //true 创建Person对象的是Functionconsole.log(p.constructor === Person); //true 创建p的是Personconsole.log(Person.prototype.constructor === Person);//true 函数prototype的constructor指向本函数console.log(p.constructor.prototype.constructor === Person);//true 根据上述关系得出的等式//特殊情况如果函数prototype的引用对象被改变,上述情况将不再存在console.log('---Example_Two---');var Student = function(name){this.name = name;};Student.prototype = {getName:function(){return this.name;}}var s = new Student('zhen');console.log(Student.constructor === Function );console.log(s.constructor === Student);console.log(Student.prototype.consturctor === Student);console.log(s.constructor.prototype.constructor === Student);//以上情况的解决办法console.log('---Example_Three---');var Animal = function(name){this.name = name;};/*Animal.prototype = {getName:function(){return this.name;}}*/Animal.prototype = new Object({getName:function(){return this.name;}});Animal.prototype.constructor = Animal; //重新覆盖prototype的constructorvar a = new Animal('zhen');console.log(Animal.constructor === Function );console.log(a.constructor === Animal);console.log(Animal.prototype.constructor === Animal);console.log(a.constructor.prototype.constructor === Animal);
如有不对请大家不吝赐教! |
|