Home >Web Front-end >JS Tutorial >The second way to write classes in javascript_js object-oriented

The second way to write classes in javascript_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:50:35903browse

2. Prototype method

Copy code The code is as follows:

/**
* Person class: defines a person, has an attribute name, and a getName method
*/
function Person(){}
Person.prototype.name = "jack";
Person.prototype.getName = function() { return this.name;}

Hang the attributes (fields) and methods of the class on the prototype.

Create a few objects to test:
Copy the code The code is as follows:

var p1 = new Person();
var p2 = new Person();
console.log(p1.getName());//jack
console.log(p2.getName()) ;//jack

It can be seen that the output is all jack, so the disadvantage of the prototype method is that the object instance cannot be constructed through parameters (generally the attributes of each object are different), and the advantages are all Object instances all share the getName method (compared to the constructor method), which does not cause memory waste .

Statement:
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