Definition and Usage
The prototype attribute gives you the ability to add properties and methods to an object.
Syntax
object.prototype.name=value
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>
Output:
20000
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
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!