Each function has a prototype (prototype) attribute. This attribute is a pointer pointing to an object. The purpose of this object is to contain the properties and methods shared by all instances of a specific type. That is, this prototype object is used to give instances Shared properties and methods.
There is a pointer to the prototype object inside each instance.
Prototype pattern
The problem with using constructors is that each method must be recreated on each instance. That is, functions with the same name on different instances of the constructor are not equal. Each constructor we create has a prototype (prototype) attribute. This attribute is a pointer pointing to an object, and the purpose of this object is to contain properties and methods that can be shared by all instances of a specific type. We use this prototype object The pattern to share the properties and methods of an instance is called the prototype pattern
//原型模式创建对象 function Person(){ } Person.prototype.name='钟女士'; Person.prototype.age=80; Person.prototype.gender='女'; var person1= new Person(); console.log(person1) //简写原型模式 Person.prototype={ constructor:Person name:'钟女士', age:80, gender:'女' }
Note: Each prototype object has a constructor attribute. Since the shorthand pattern overrides the default prototype object, the constructor will also be redefined. It no longer points to his constructor, so you can write a constructor attribute to point to his constructor
The above is the detailed content of what is prototype in js. For more information, please follow other related articles on the PHP Chinese website!