JavaScript Learning notes 3--creating objects

Source: Internet
Author: User
Tags instance method uppercase letter

This article is mainly a summary of the sixth chapter of the Advanced programming of JavaScript (object-oriented programming), which is seen at least 4 times in this chapter of the book. This chapter mainly deals with the creation and inheritance of objects. There are at least 6 types of objects created and inherited, plus some method attributes, which can easily be confusing. Therefore, it is necessary to the content of this chapter to reason, later forgot to come to see.

Due to the limitation of the length of the article, this article mainly deals with creating objects.

1 creating objects 1.1 general methods

Use object or the method that takes the literal.

1 var o = {a:1}; 2 var o2=New  Object (); 3       O2.a=1;

Cons: Creating many objects with the same interface produces a lot of duplicated code.

1.2 Factory mode
 function   parent (name,age) { var  child = new   Object ();      Child.name  =name;      Child.age  =age; Child.sayhi  =function   () {Console.log (    /span> "Hi" );   return   child;  };       var  x = Parent ("Tom", 12);  Console.log (X.name);   // tom  x.sayhi (); // hi  

The function parent is able to construct a child object that contains all the necessary information based on the parameters that are accepted. This function can be called indefinitely, and will return an object containing two properties and a method.

Solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (that is, how to know the type of an object).

1.3 Constructor Mode

For the constructor of the name, learn Java or C + + students should be aware of, in JS is similar.

Use the constructor to rewrite the above example as follows:

function Parent (name,age) {      this. name=name;        this. age= age;       this. sayhi=function() {        console.log ("Hi");    };   } var New Parent ("Tom",N);      Console.log (x.name);   // Tom    X.sayhi ();  // Hi

For constructors, we need to add the keyword new at the time of the call . Note that the constructor always starts with an uppercase letter, and the non-constructor always starts with a lowercase letter.

Compared with the factory model, there are several differences in the following areas:

    • Create object without display;
    • The properties and methods are assigned directly to the This object;
    • There is no return statement.

Cons: The disadvantage of using constructors is that each method needs to be recreated on each instance.

1.4 Prototype Mode

Each function we create has a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type. The advantage of using a prototype object is that you can have all of the object instances share the properties and methods that they contain.

function Parent (name,age) {      Parent.prototype.name=name;      Parent.prototype.age= Age;      Parent.prototype.sayHi=function() {        console.log ("Hi");    };   } var New Parent ("Tom",N);      Console.log (x.name);   // Tom    X.sayhi ();  // Hi

Disadvantage: The advantage is its disadvantage, the method attributes can be shared. The following example can be seen in detail

functionParent (name,age) {Parent.prototype.name=name; Parent.prototype.age=Age ; Parent.prototype.arr=["123", "we"]; Parent.prototype.sayHi=function() {Console.log ("Hi");   }; }varx =NewParent ("Tom", 12); vary =NewParent ("Tom1", 12); X.arr.push ("X"); Y.arr.push ("Y"); Console.log (X.arr);//["123", "we", "X", "Y"]Console.log (Y.arr);//["123", "we", "X", "Y"]

Object x modifies its own properties to affect the Y object, as well as for Y. This is obviously unreasonable ah, too terrible!

1.5 Combining the constructor pattern with the prototype mode
functionParent (name,age) {
  //Only leave the attribute here as defined, and the method is placed in the prototype object this.name=name; This.age=Age ; }//The first wayParent.prototype.sayhi=function() {Console.log ("Hi");}; //The second way//because the object literal is used, the constructor attribute must be corrected;Parent.prototype={constructor:parent, Sayhi:function() {Console.log ("Hi"); } }varx =NewParent ("Tom", 12); Console.log (X.name); //TomX.sayhi ();//Hi

In this example, the instance properties are defined in the constructor, and the properties constructor and methods shared by all instances are defined in the prototype.

Is the most widely used and most recognized method of creating custom types.

--------------------------feel some kind of pervert in the back of the way--------------------------------

1.6 Dynamic Prototype mode
functionParent (name,age) { This. name=name;  This. age=Age ; if (typeof this.sayhi! = "function" ) { Parent.prototype.sayHi=function() {Console.log ("Hi");      }; }}varx =NewParent ("Tom", 12);  Console.log (X.name); //TomX.sayhi ();//Hi

Check to see if an existing method is valid before deciding whether to initialize the prototype.

1.7 Parasitic constructor mode

The parasitic constructor pattern can be used when none of the preceding types is applicable. The basic idea of this function is to create a function that simply encapsulates the code that creates the object, and then returns the newly created object.

 function   parent (name,age) { var  child = new   Object ();      Child.name  =name;      Child.age  =age; Child.sayhi  =function   () {Console.log (    /span> "Hi" );   return   child;  };       var  x = Parent ("Tom", 12);  Console.log (X.name);   // tom  x.sayhi (); // hi  

But in fact, the same as the factory model, you TM is teasing me?????

1.8 Secure Constructor Mode

The secure constructor follows a pattern similar to the parasitic constructor pattern, but has a difference of two points: one is that the instance method of the newly created object does not refer to this; The second is to call the constructor without using the new operation.

 function   Parent (name,age) { var  o=new   Object (); 
//private variable or method var name=age; O.sayname =function () {
//name not preceded by this console.log (name + "+age)} return o;} var x = Parent ("Tom", 12 // tom

The variable x holds a secure object, and there is no other way to access its data members than to call the Sayname () method.

JavaScript Learning notes 3--creating objects

Related Article

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.