Home > Article > Web Front-end > Detailed explanation of javascript prototype pattern usage examples_javascript skills
The examples in this article describe the usage of JavaScript prototype mode. Share it with everyone for your reference. The specific analysis is as follows:
Generally after understanding the disadvantages of factory pattern and constructor pattern, you will know why prototype pattern is needed
Definition of prototype pattern i: Every function has a prototype attribute, which is an object whose purpose is to contain properties and methods that can be shared by all instances of a specific type. For example, in the sayInformation() method in the constructor model, if two instances are declared, the sayInformation method must be constructed twice, but it is not necessary to declare it twice. This is why the prototype pattern appears (Nima, those blogs on the Internet all have Is it nonsense, or is it easy to understand when reading a book), after sayInformation() is declared as prototype mode, the instance is shared, and there is no need to declare it twice
function Person(){} Person.prototype.name="jack"; Person.prototype.age=10; Person.prototype.sayInformation=function() { console.log("my name is"+this.name+" age is"+this.age); } var person1 = new Person(); person1.sayInformation(); console.info(person1.name); //来自原型的属性name person1.name="Greg"; //修改实例的name属性 console.info(person1.name); //来自实例的属性name delete person1.name ; //来自实例的属性,这里删除的是实例的属性,但是原型的属性依然存在 console.info(person1.name); //来自原型的属性name var person2 = new Person(); person2.sayInformation(); console.info(person1.hasOwnProperty("name")); //hasOwnProperty检查属性是属于实例还是原型中,如果是实例中就返回true console.info(person1.name==person2.name); console.info(person1.sayInformation==person2.sayInformation); console.info(person1.constructor); //指向person1的构造函数 //原型更加简便的写法 function Person2(){} Person2.prototype={ name:"jack", age:29, sayInformationfunction:function() { console.log("my name is"+this.name+" age is"+this.age); } }
I hope this article will be helpful to everyone’s JavaScript programming design.