Home > Article > Web Front-end > Detailed explanation of the three basic ways of generating objects in js (factory mode, constructor mode, prototype mode)
1. Factory pattern
Factory pattern is a well-known design pattern in the field of software engineering. Since classes cannot be created in ECMAScript, functions are used to encapsulate objects with specific interfaces. The implementation method is very simple, that is, create an object within the function, assign properties and methods to the object, and then return the object.
function a(name){ var b = new object(); b.name = name; b.say = function(){ alert(this.name); } return b }
The function generates the b object internally and returns it.
2. Constructor pattern
function Person(name, url) { //注意构造函数名第一个字母大写 this.name = name; this.url = url; this.alertUrl = alertUrl; } function alertUrl() { alert(this.url); }
Because every time an object is constructed, an alertUrl method will be generated, which is a waste of resource space, so use The alertUrl method is written globally to save space, but writing it this way violates the original intention of object-oriented programming. The following prototype mode is better.
3. Prototype pattern
Every function we create has a prototype attribute. This attribute is a pointer pointing to an object, and the purpose of this object is to contain information that can be used by a specific Properties and methods shared by all instances of a type. The advantage of using a prototype object is that all object instances can share the properties and methods it contains.
function Person(){ } Person.prototype.name = "bill"; Person.prototype.address = "GuangZhou"; Person.sayName = function (){ alert(this.name); } var person1 = new Person(); var person2 = new Person(); //测试代码 alert(person1.name); // bill alert(person2.name); // bill person1.sayName(); //bill person2.sayName(); //bill person1.name = "666"; alert(person1.name); // 666 alert(person2.name); // bill person1.sayName(); //666 person2.sayName(); //bill
Every function we create has a prototype attribute, which is actually a pointer pointing to an object.
When a person object such as person1 is constructed, its default name attribute is bill. If you want to change the name value, you must operate on person1.name. This just changes the name attribute of this object. alert(person1.prototype.name) still pops up a bill, that is, the name attribute on the prototype
The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.
For more detailed explanations of the three basic ways of generating objects in js (factory mode, constructor mode, prototype mode), please pay attention to the PHP Chinese website for related articles!