This article mainly introduces three basic methods (factory mode, constructor mode, and prototype mode) for js to generate objects, which has some reference value. If you are interested, please refer to 1. factory Model
The factory model is a well-known design model in the software engineering field. Because classes cannot be created in ECMAScript, function encapsulation is used to create objects with specific interfaces. The implementation method is very simple, that is, to create an object in the function, assign attributes 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 and returns it.
2. constructor Mode
Function Person (name, url) {// note that the first letter of the constructor name is capitalized this. name = name; this. url = url; this. alertUrl = alertUrl;} function alertUrl () {alert (this. url );}
Every time an object is constructed, an alertUrl method is generated, which is too resource space-consuming. Therefore, the alertUrl method is written globally to save space. However, this method violates the original intention of object-oriented programming, the following prototype is better.
3. prototype mode
Each function we create has the prototype attribute, which is a pointer pointing to an object, the purpose of this object is to include attributes and methods that can be shared by all instances of a specific type. The advantage of using a prototype object is that all object instances can share its attributes and methods.
Function Person () {} Person. prototype. name = "bill"; Person. prototype. address = "GuangZhou"; Person. sayName = function () {alert (this. name);} var person1 = new Person (); var person2 = new Person (); // test code alert (person1.name); // billalert (person2.name ); // billperson1.sayName (); // billperson2.sayName (); // bill person1.name = "666"; alert (person1.name); // 666 alert (person2.name); // billperson1.sayName (); // 666person2. sayName (); // bill
Each function we create has the prototype attribute, which is actually a pointer pointing to an object.
After constructing a person object such as person1, its default name attribute is bill. If you want to change the name value, you need to operate on person1.name. This only changes the name attribute of the object. Alert (person1.prototype. name) is still the pop-up bill, that is, the name attribute on the prototype
The above is all the content of this article. I hope it will help you learn and support PHP.
For more details about the three basic methods (factory mode, constructor mode, and prototype mode) for js object generation, please follow the PHP Chinese network!