<code><script type="text/javascript"> function Person(){} Person.prototype.array = new Array("Koji", "Luo"); Person.prototype.showArray = function(){ alert(this.array); } var obj1 = new Person(); //生成一个Person对象 var obj2 = new Person(); obj1.array.push("Kyo"); //向obj1的array属性添加一个元素 obj1.showArray(); //Koji,Luo,Kyo obj2.showArray(); //Koji,Luo,Kyo </script> </code>
If an element is added to the array of obj1, it will also be added to the array of obj2.
Is the array they inherit a pointer? What everyone has is the array in the prototype object?
<code>//最后问一个很奇怪的问题(prototype中的array难道也只是一个指针?) </code>
Thank you everyone..
<code><script type="text/javascript"> function Person(){} Person.prototype.array = new Array("Koji", "Luo"); Person.prototype.showArray = function(){ alert(this.array); } var obj1 = new Person(); //生成一个Person对象 var obj2 = new Person(); obj1.array.push("Kyo"); //向obj1的array属性添加一个元素 obj1.showArray(); //Koji,Luo,Kyo obj2.showArray(); //Koji,Luo,Kyo </script> </code>
If an element is added to the array of obj1, it will also be added to the array of obj2.
Is the array they inherit a pointer? What everyone has is the array in the prototype object?
<code>//最后问一个很奇怪的问题(prototype中的array难道也只是一个指针?) </code>
Thank you everyone..
First of all, you must understand how inheritance is implemented. .
1. The constructor has a prototype
attribute.
2. Each instance of a constructor has a __proto__
prototype attribute pointing to its constructor.
3. When accessing an attribute that does not exist in an object itself, it will be searched on the prototype of its constructor through __proto__
.
4. So calling obj1.array
accesses Person.prototype.array
; calling obj2.array
also accesses Person.prototype.array
.
5, obj1
and obj2
all share this array
.
6. So it has nothing to do with passing by value or passing by reference. Originally, each instance accessed a prototype
Each instance did not save a copy of the constructor prototype...