JavaScript attribute prototype for adding properties and methods to objects

黄舟
Release: 2017-11-04 10:27:24
Original
2378 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:

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 'watching movies'; } var boy=new Person('keith',180); var girl=new Person('rascal',153); console.log(boy.name); //'keith' console.log(girl.name); //'rascal' 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!