7 ways in which OOP creates objects

Source: Internet
Author: User
Tags hasownproperty

I write the JS code, can say has been a process-oriented way of writing, in addition to some of the objects used to encapsulate data or jquery plug-ins, you can say that the native objects know little. So I took the "JavaScript Advanced Programming 3rd Edition" evil complement a bit, here sit down summary notes, belong to rookie level, the great god please directly ignore.

1. Factory mode

1/** 2  * Factory mode 3 *  /4 function Createperson (name,age,job) {5     var o = new Object (); 6     o.name = name; 7     O.age  = age, 8     o.job = job, 9     o.sayname = function () {Ten         console.log (this.name);     };12     // Equivalent to  o.sayname = new Function ("Console.log (this.name);");     return o;14}15 var p1 = Createperson (' lvyahui1 ', ' n ', ' Devloper '), var p2 = Createperson (' lvyahui2 ', +, ' Desigen ') ); P1.sayname (); P2.sayname (); Console.log (P1.sayname = = = P2.sayname); False

There are a number of problems with this approach, such as the way multiple objects are independent and useless to share. Cannot determine the type of an object

2. Constructor mode

1/** 2  * Constructor Mode 3 *  /4 function person (name,age,job) {5     this.name = name, 6     this.age = age; 7     THIS.J OB = job; 8     this.sayname = function () {9         console.log (this.name),     };11}12 var pp1 = new Person (' lvyahui1 ', ' Dev ') ; var pp2 = new Person (' lvyahui2 ', ' n ', ' Desien '); Pp1.sayname (); Pp2.sayname (); Console.log (Pp1.constructor = = = person);  true17 console.log (pp2.constructor = = = person);  true18 console.log (pp1 instanceof Object);  true19 Console.log (pp2 instanceof person);  true

This approach solves the problem of object type judgement, but does not solve the problem of method sharing, and the method is still created in each object again. To solve this problem, you can do the following

1 function Home (name,age,job) {2     this.name = name;3     this.age = age;4     this.job = job;5     this.sayage = Sayag E;6}7 function Sayage () {8     console.log (this.age); 9}

However, this has brought new problems, the function defined in the global scope can only run in the object environment, violating the global concept, and when the method to be defined is very many stone monkeys. It is necessary to define n-many global functions without encapsulation.

Also, it is important to note that the constructor is also a function, and the only difference from the normal function is that it is called differently. As below, we can take it as a normal function, so that the properties and methods will be bound to the browser Global Execution Environment window, or bound to another object to run, bind property methods to other objects

The 1//constructor is also a function of 2//  1 3 var person = new Person (' hahha ', ' + ', ' ddd '), 4//  2 do normal function 5 person (' window ', one, ' 2323dd '); 6/ /window.sayname (); 7  8//  3 use 9 var o = new object in the scope of another object (), Person.call (O, ' Lvyahui ', Max, ' 2323 '), O.sayname ();

3. Prototype mode

Each function in JS has a special attribute-prototype (prototype), which is a pointer to an object. This object contains all the properties and methods that are shared by the object created with this function for the constructor, first look at the following code

1/** 2  * Prototype mode 3  */4 function Dog () {} 5 Dog.prototype.name = ' A mi '; 6 Dog.prototype.age = 1; 7 Dog.prototype.say Name = function () {8     Console.log (this.name), 9}10 var d1 = new Dog (),     d2 = new Dog (); D1.sayname (); d2.s Ayname (); Console.log (D1.sayname = = = D2.sayname);  True16 Console.log (Dog.prototype.isPrototypeOf (D1));  true17 Console.log (object.getprototypeof (D1));//return value of [[prototype]] Console.log (object.getprototypeof (D1) = = = Dog.prototype);

The properties and methods are added here to the prototype object of the function. In the 4th line of code I define the dog construction method, which points to the constructor attribute of dog's prototype object to dog. The 5-7-line code adds 2 properties and a method to the dog's prototype object.

Line 11th, 12 lines of code created two object instances, each of the two instances contains only a special property [[Prototype]], which points to the Prototype of the constructor, the Prototype property of the constructor points to the prototype object, The constructor property of the prototype object refers to the dog construction method, here compared around, I directly take the book above the picture for everyone to see, a little modification, the figure is the person constructor, here is really sorry, not in the Ubuntu system to find a good drawing tools, can only be done, You can introduce it to me if you know it.

In addition, this figure is also omitted in an inheritance relationship, that is, the person object is actually inherited obejct, this is the default rule, other languages also have. This is also the reason that JS objects are created with object methods and properties.

One more, the code in the above

    • The isPrototypeOf method returns whether the [[Prototype]] property of the parameter object points to the object that called isPrototypeOf.
    • The Getprototype method returns the value of the [[Prototype]] property.

An important concept of the prototype is the attribute search (which I think is also the attribute), from the instance object to the upstream of the prototype chain search, if found to stop the search, so if we add the prototype in the instance of the properties or methods, the prototype chain will be masked out of the properties or methods. Look at the code below.

1 d1.name = ' Sai Mao ';    Mask the properties in the prototype 2 console.log (d1.name); 3//To restore the properties in the prototype, you must display the properties in the deleted instance 4 delete d1.name;5 console.log (d1.name);

As you can see, you can use Delete to restore the properties in the prototype, and the following method can be used to detect whether a property is in an instance object or in a prototype chain.

1//Detect whether a property is in an instance, or 2 D1.name = ' HHHH ' in the prototype; 3 Console.log (D1.hasownproperty (' name ')); Returns true only if the given property exists in the object instance 4 delete d1.name; 5 Console.log (D1.hasownproperty (' name ')); 6  7//using the In operator alone, returns true if the property is found in the object 8 d1.name = ' DSFDSFSD '; 9 console.log (' name ' in D1);  True10 console.log (' name ' in D2);  TURE11 12//use both the hasownproperty and in operators to determine whether this property is in the prototype or in the instance (object,name) {     return!object.hasownproperty (name) && name in object;15}16 console.log (' D1 hasprototypeproperty: ' + Hasprototypeproperty (d1, ' name ')); Console.log (' D2 hasprototypeproperty: ' +hasprototypeproperty (D2, ' name '));

Exceptions have a simpler way of prototyping

1//Simpler prototype Syntax 2 function Cat () {} 3 Cat.prototype = {4     name    :   ' Mimi ', 5 age     :   6,     job     : c8/> ' Doubi ', 7     sayname:   function () {8         console.log (this.name); 9     }10};11 var cat = new Cat (); Sole.log (cat instanceof Object), Console.log (cat instanceof Cat), console.log (Cat.constructor = = cat);//false16 Console.log (Cat.constructor = = = Object);//true

This approach actually re-creates an object in a literal way and assigns a value to the prototype pointer. It discards the original prototype object, so it is obvious that the constructor property of the prototype object no longer points to cat, but instead points to obejct, there are several ways to fix the constructor, such as when defining the literal object, it shows that the constructor property is defined as Cat, You can also use the following method.

1//Reset Cat's Constructor property 2 Cat.prototype.constructor = Cat; 3//  But this constructor becomes enumerable of 4 var Cat_keys = Object.keys (Cat.prototype); 5 Console.log (Cat_keys);//[' name ', ' age ', ' J OB ', ' sayname ', ' constructor '] 6 Console.log (Object.keys (cat));//[] 7  8//Reset constructor Properties 9 Object.defineproperty (Cat.prototype, ' constructor ', {     enumerable:false,11     value:cat12}); Cat_keys = Object.keys ( Cat.prototype); Console.log (Cat_keys);//[' name ', ' age ', ' job ', ' sayname ']

Prototype mode is also not a problem, such as bad to pass parameters to the constructor function. The biggest problem is the sharing of the prototype properties of the reference type, see the following code

1//Prototype mode The biggest problem is the property sharing problem with reference types 2  3 function House () {} 4  5 House.prototype = {6     constructor:house, 7     Friend s:[' Lvyahui ', ' d '] 8}; 9 var h1 = new House (), one     H2 = new House (), H1.friends.push (' Li '), Console.log (h1.friends),//[' Lvyahui ', ' d ', ' Li ']14 console.log (h2.friends);//[' Lvyahui ', ' d ', ' Li ']

4. The pattern of the combination of the constructor and the prototype object mode

The combination pattern can be said to absorb the advantages of the constructor pattern and prototype pattern, which ensures that each object instance has its own independent properties and methods, and there are properties and methods that can realize the sharing.

1/** 2  * Common way, combined using constructor mode and prototype mode 3  */4  5 function Movie (name,length) {6     this.name= name; 7     this.length = length; 8     this.links = [' H1 ', ' H2 ']; 9}10 movie.prototype = {One     constructor:movie,12     sayname:function () {         Console.log (this.name);     }15};16 var m1 = new Movie (' Diany1 ', +),     m2 = new movie (' Diany2 ', 23); 18 M1.links.push (' H3 '); Console.log (m1.links); Console.log (m2.links); Console.log (m1.links = = m2.links); 23 Console.log (M1.sayname = = = M2.sayname);

This way set the length of the family, I think this way should be used more than the bar (I have not graduated, the actual situation in the enterprise is not very familiar with, know can quietly tell me)

There is, of course, a better way to do this, the so-called dynamic prototype pattern

5. Dynamic prototype mode

1 function Miss (name,age) {2     this.name = name; 3     this.age = age; 4  5     if (typeof this.sayname! = ' function ') {6         Miss.prototype.sayName = function () {7             console.log (this.name); 8         } 9     }10}11 var Miss = new Miss (' Lvyahui ', ); Miss.sayname ();

This way, while maintaining the advantages of the combined model, let the code look better and more secure.

6. Parasitic tectonic pattern

In this way, with the Factory mode, there is only one difference, creating the object in the form of the new constructor, as follows, noting that it differs from the factory schema only when creating the object (16 rows new)

1/** 2  * Parasitic construction mode 3  *  /4 5 function CreatePerson2 (name,age,job) {6     var o = new Object (); 7     o.name = Nam E 8     o.age  = age; 9     o.job = job;10     o.sayname = function () {One         console.log (this.name);     };13     //equivalent to  o.sayname = new Function ("Console.log (this.name);");     return o;15}16 var p1 = new CreatePerson2 (' Lvyahui1 ', ' devloper ');

7. Secure Structural function mode

This pattern is based on the concept of a secure object, which is an object that has no public properties and that does not use this object in its methods. We all know that JS in this has been a headache for people.

The safe mode is similar to the parasitic pattern, except that

    • Constructors are not called by the new operator
    • Do not use this in an instance method of a row creation object
1/** 2  * Secure construction Mode 3  */4 function Girl (name,age) {5     var o = new Object (); 6     o.sayname = function () {7         C Onsole.log (name); 8     }; 9     o.sayage = function () {         console.log (age);     };12     return o;13}14 var gril = Girl (' d ', 21); 15 Console.log (Gril.sayname ()); Console.log (Gril.sayage ()); +//    output//D19/    /UNDEFINED20/    /    2121//    undefined22//Why?    

Do you know why this output is so? Tell me the message you know.

OK, so much to write, to summarize, the original creation of JS object of the most pervasive method should be the combination mode it.

Category: JavaScript Tags: javascript, frontend, JS oop, JavaScript Object oriented

7 ways in which OOP creates objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.