javascript - JS Ask a question about a new object inheriting prototype's Array?

WBOY
Release: 2016-08-27 09:06:53
Original
974 people have browsed it

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

Thank you everyone..

Reply content:

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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...

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template