Home > Web Front-end > JS Tutorial > body text

JavaScript attribute prototype for adding properties and methods to objects

黄舟
Release: 2017-11-04 10:27:24
Original
2473 people have browsed it

Definition and Usage

The prototype attribute gives you the ability to add properties and methods to an object.

Syntax

object.prototype.name=value
Copy after login

Example

In this example, we will show how to use the prototype attribute to add properties to an object:

<script type="text/javascript">

function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}

var bill=new employee("Bill Gates","Engineer",1985);employee.prototype.salary=null;bill.salary=20000;

document.write(bill.salary);

</script>
Copy after login

Output:

20000
Copy after login

The role of the prototype attribute

In order to solve the shortcoming that attributes cannot be shared between object instances of the constructor, js provides the prototype attribute.

Every data type in js is an object (except null and undefined), and each object inherits from another object. The latter is called a "prototype" object, and only null Except, it doesn't have its own prototype object.

All properties and methods on the prototype object will be shared by the object instance.

When an object instance is generated through a constructor, the prototype of the object instance will point to the prototype attribute of the constructor. Each constructor has a prototype attribute, which is the prototype object of the object instance.

function Person(name,height){
this.name=name;
this.height=height;
} 
Person.prototype.hobby=function(){
return &#39;watching movies&#39;;
}
var boy=new Person(&#39;keith&#39;,180);
var girl=new Person(&#39;rascal&#39;,153); 
console.log(boy.name); //&#39;keith&#39;
console.log(girl.name); //&#39;rascal&#39;
console.log(boy.hobby===girl.hobby); //true
Copy after login

In the above code, if the hobby method is placed on the prototype object, then both instance objects share the same method. What I hope everyone can understand is that for constructors, prototype is the attribute of the constructor; for object instances, prototype is the prototype object of the object instance. So prototype is both an attribute and an object.

The above is the detailed content of JavaScript attribute prototype for adding properties and methods to objects. For more information, please follow other related articles on the PHP Chinese website!

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