Javascript Note: deeply analyzes the creation of objects in javascript (I)

Source: Internet
Author: User
When I read the jQuery source code, I often think that those factors will make me unable to read the code. Which of the most critical factors is the earliest thought of as the architectural design of jQuery, when I finally found the jQuery architectural design portal, I found that the skillful use of the basic javascript syntax is the reference for reading the source code... syntaxHighlighter. all ();

When I read the jQuery source code, I often think that those factors will make me unable to read the code. Which of the most critical factors is the earliest thought of as the architectural design of jQuery, when I finally found the entry to jQuery's architectural design, I found that the skillful use of the basic javascript syntax is the key to reading the source code. Therefore, it is necessary to review the basic javascript knowledge system, in addition, the research of jQuery source code is to deepen and flexibly use the basic javascript knowledge. I want to introduce jQuery in the future and link it with my basic javascript knowledge, this will certainly give better answers to various difficult questions.
After studying javascript in depth recently, some individuals will: Object-oriented programming is efficient and flexible, and it is now the only programming method that can make code more robust. If we leave out those mysterious ideas such as abstract classes, my own understanding of object-oriented programming is reuse and encapsulation. Reuse is to minimize repeated code writing. encapsulation is to put some logic with high coupling into a program block, and try to prevent the content from being influenced by the outside world. The final conclusion is that excellent javascript code is object-oriented.
Today we will talk about how to build javascript objects.
The ECMA-262 defines an object as a set of unordered properties that can contain basic values, objects, or functions. Javascript objects are actually map in java, that is, key-value pairs.
There are three ways to create an object in javascript:
Method 1: use an Object
Method 2: Use Constructor
Method 3: object initialization
1. Build an Object using the Object. The Code is as follows:
// Directly create an Object using the Object

Var obj = new Object ();
Obj. id = '001 ';
Obj. name = 'My name is obj ';
Obj. teststring = 'test obj ';
Obj. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}

Obj. sayHello (); // id: 001 @! @ Name: My name is obj @! @ Teststring: Test obj
Obj ['sayhello'] (); // id: 001 @! @ Name: My name is obj @! @ Teststring: Test obj
Var str = 'sayhello ';
Obj [str] (); // id: 001 @! @ Name: My name is obj @! @ Teststring: Test obj
(Note: Here I use two methods to access object attributes: vertex operator and square brackets operator, which are equivalent, but square brackets seem to be more powerful, and variables can be placed in square brackets)
This is the most common and intuitive method for creating objects, but its disadvantage is too obvious, that is, code reusability is very low. When we think of an object, we create an object, if so, a large amount of repeated code is generated. Therefore, javascript programmers introduce the factory mode into javascrip programming. Please refer to the following code:
// Create an object in factory Mode

Function createObj (id, name, teststring)
{
Var o = new Object ();
O. id = id;
O. name = name;
O. teststring = teststring;
O. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
Return o;
}
Var obj = createObj ('002 ', 'My Name is obj2', 'test Obj2 ');
Obj. sayHello (); // id: 002 @! @ Name: My Name is obj2 @! @ Teststring: Test Obj2
Obj ['sayhello'] (); // id: 002 @! @ Name: My Name is obj2 @! @ Teststring: Test Obj2
Var str = 'sayhello ';
Obj [str] (); // id: 002 @! @ Name: My Name is obj2 @! @ Teststring: Test Obj2
The factory mode solves the problem of creating similar objects. If you leave it alone to construct object recognition, the factory mode is perfect. If your javascript Application is not too complex, we recommend that you use the factory mode to construct an object, which is highly readable. (Writing to the engineering mode, it seems that some annotations in linxu jQuery are not correct. This will be corrected later ).
2. Through Constructors
In my previous blog post "javascript notes: Past javascript (from the origin of javascript, let's talk about its inheritance)", I talked about some javascript object-oriented design ideas from the origin of javascript, the javascript constructor is designed. Almost all objects built using constructors use the new operator. constructors in javascript are special. There is no class concept in javascript, and the new is followed by the constructor, let's look at the following code:
// Create an object using the constructor

Function Obj (id1, name1, teststring1)
{
This. id = id1;
This. name = name1;
This. teststring = teststring1;
This. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
}

Var obj = new Obj ('003 ', 'My Name is obj3', 'test obj3 ');
Obj. sayHello (); // id: 003 @! @ Name: My Name is obj3 @! @ Teststring: Test Obj3
Obj ['sayhello'] (); // id: 003 @! @ Name: My Name is obj3 @! @ Teststring: Test Obj3
Var str = 'sayhello ';
Obj [str] (); // id: 003 @! @ Name: My Name is obj3 @! @ Teststring: Test Obj3
The constructor is very similar to the factory model in terms of code. When I was learning javascript, I looked at a separate method. Thinking always confuses the two with inertia, if the two functions are put together, the difference is that functions in javascript are given too many functions. If they are used in a large program in turn, it is strange to ignore the head. In fact, through the difference between the two construction objects, I can divide the use of functions into constructor and function. I will focus on the two methods below. The bottom may not be comprehensive here. If any expert can see them, I can add and give some advice.
First, I will remove the this pointer of each attribute in the method, but the this pointer referenced in sayHello will not be removed. The Code is as follows:
// In-depth analysis of constructor 1
Function Obj (id1, name1, teststring1)
{
Id = id1;
Name = name1;
Teststring = teststring1;
SayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
}
Var obj = new Obj ('004 ', 'My Name is obj4', 'test obj4 ');
SayHello (); // id: undefined @! @ Name :@! @ Teststring: undefined
Window. sayHello (); // id: undefined @! @ Name :@! @ Teststring: undefined
Obj. sayHello (); // obj. sayHello is not a function [interrupted in this error] obj. sayHello ();
This always points to obj, and this in the sayHello method. the value of the attributes such as id is undefined, indicating that the function object of Obj does not have the id, name, and teststring attributes. Even the sayHello method is not defined in Obj, but sayHello () is directly used (); we can find the sayHello method, and finally we use window. sayHello (); To Know That sayHello is defined in the window. If I remove all this in Obj, the Code is as follows:
// In-depth analysis of constructor 2

Function Obj (id1, name1, teststring1)
{
Id = id1;
Name = name1;
Teststring = teststring1;
SayHello = function ()
{
Console. log ('Id: '+ id + '@! @ Name: '+ name + '@! @ Teststring: '+ teststring );
}
}
Var obj = new Obj ('005 ', 'My Name is obj5', 'test obj5 ');
SayHello (); // id: 005 @! @ Name: My Name is obj5 @! @ Teststring: Test Obj5
Window. sayHello (); // id: 005 @! @ Name: My Name is obj5 @! @ Teststring: Test Obj5
Console. log (id); // 005
Console. log (name); // My Name is obj5
Console. log (teststring); // Test Obj5
Console. log (window. id); // 005
Console. log (window. name); // My Name is obj5
Console. log (window. teststring); // Test Obj5
I drew the following conclusion from the above content:
1. javascript can be used for Object-Oriented Programming. We cannot regard it as a process-oriented language;
2. Object creation in javascript is special, especially because it is simplified compared with the traditional object-oriented language, and simplified to directly using constructors to create objects;
III. in javascript, a function can be used as a function or a constructor identifier (you can also view it as a class ), the difference between the constructor and the function is new;
4. if the constructor is used to create an object, it is encapsulated like other object-oriented languages. In other words, the attributes or methods defined in the constructor belong to the object, the way to make it belong to this object is to use the this pointer, otherwise the attributes and methods will belong to the window object.
If we do not use the new operator, use the function directly, for example, the following code:
// In-depth analysis function 1 www.2cto.com

Function Obj (id1, name1, teststring1)
{
This. id = id1;
This. name = name1;
This. teststring = teststring1;
This. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
}
Obj ('006 ', 'My Name is obj6', 'test obj6 ');
SayHello (); // id: 006 @! @ Name: My Name is obj6 @! @ Teststring: Test Obj6
Window. sayHello (); // id: 006 @! @ Name: My Name is obj6 @! @ Teststring: Test Obj6
Console. log (id); // 006
Console. log (name); // My Name is obj6
Console. log (teststring); // Test Obj6
Console. log (window. id); // 006
Console. log (window. name); // My Name is obj6
Console. log (window. teststring); // Test Obj6
Directly calling the function, the this pointer is directed to the window, that is, the global object. I have seen a sentence: No matter where the function is called directly, this in it points to the global. The following code shows how to directly call a function:
// In-depth analysis function 2

Function OuterObj (id1, name1, teststring1)
{
This. id = id1;
This. name = name1;
This. teststring = teststring1;
This. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}

Function InnerObj (id2, name2, teststring2)
{
This. id = id2;
This. name = name2;
This. teststring = teststring2;
This. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
}

Var innerVal = new InnerObj ('20140901', 'innerobj ', 'test InnerObj'); // true
Console. log (innerVal instanceof InnerObj );
InnerVal. sayHello (); // id: 101 @! @ Name: InnerObj @! @ Teststring: Test InnerObj

InnerObj ('20140901', 'innerobj0', 'test innerobj0 ');
}

Var outObj = new OuterObj ('007 ', 'My Name is obj7', 'test obj7 ');
OutObj. sayHello (); // id: 007 @! @ Name: My Name is obj7 @! @ Teststring: Test Obj7
SayHello ();//
Window. sayHello (); // id: 102 @! @ Name: InnerObj0 @! @ Teststring: Test InnerObj0
Console. log (id); // 102
Console. log (name); // InnerObj0
Console. log (teststring); // Test InnerObj0
It can be seen that the methods and functions that the function calls this point all point to the window, that is, the global object.
3. object initialization
Object initialization methods are also called literal object construction methods in some books, but I prefer object initialization methods. The Code is as follows:
// Object initialization

Var obj = {
Id: '008 ',
Name: 'My Name is obj8 ',
Teststring: 'test obj8 ',
SayHello: function (){
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
};
Obj. sayHello (); // id: 008 @! @ Name: My Name is obj8 @! @ Teststring: Test Obj8
Obj ['sayhello'] (); // id: 008 @! @ Name: My Name is obj8 @! @ Teststring: Test Obj8
Var str = 'sayhello ';
Obj [str] (); // id: 008 @! @ Name: My Name is obj8 @! @ Teststring: Test Obj8
This method is one of my favorite ways to build objects. A javascript master once suggested to build an empty object, preferably var obj = {}, this statement indicates that var obj = {} and var obj = new Object (); are equivalent. The var obj = {} method is more concise, avoiding the tedious Writing of o. id; o. name and so on. jQuery source code uses a lot of such methods to construct objects.
The above are three methods I know to build objects in javascript. Next I will take a different perspective to understand the knowledge of javascript Object building. First, let's look at a piece of java code:
Public class Obj {

Public static String staticParams = "static attribute, which belongs to the class ";

Private String objId = "the number is private to the object ";

Public String objName = "the name is public to the object ";

// Constructor
Public Obj (){}
}
The attributes or methods of javascript objects can also be divided into attributes and methods of classes, attributes or methods of objects, public attributes and methods, and private attributes and methods.
1. attributes and methods of classes: objects can be initialized as class attributes and methods. This definition is widely used in jQuery;
2. attributes or methods of objects: Construct objects using constructors. The attributes and Methods pointed to by the this pointer are all objects;
3. Public attributes and Methods: attributes and methods in javascript are inherently public;
4. private attributes and Methods: this can only be implemented through simulation in javascript. This simulation generally uses the scope principle, for example, using var to define objects in a function, the object scope is inside the function, so it cannot be accessed outside the function. This is the private variable and method.
The property and method operations in the above object are proprietary. Similar objects built in the same way cannot share information, so how can we make similar objects share information? This uses prototype.
In javascript, each function has a prototype attribute, which is a pointer to an object. The purpose of this object includes the attributes and methods that can be shared by all instances of a specific type.
The Code is as follows:
// Prototype

Function Obj (id1, name1, teststring1)
{
This. id = id1;
This. name = name1;
This. teststring = teststring1;
This. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
}

Obj. prototype. objflag = 'self-built Obj object ';
Obj. prototype. proSayHello = function ()
{
Console. log ('Hello World and Obj ');
}

Var obj1 = new Obj ('008 ', 'My Name is obj8', 'test obj8 ');
Var obj2 = new Obj ('009', 'My Name is obj9', 'test obj9 ');

Obj1.sayHello (); // id: 008 @! @ Name: My Name is obj8 @! @ Teststring: Test Obj8
Obj2.sayHello (); // id: 009 @! @ Name: My Name is obj9 @! @ Teststring: Test Obj9
Obj1.proSayHello (); // Hello World and Obj
Obj2.proSayHello (); // Hello World and Obj
Console. log (obj1.objflag); // self-built Obj object
Console. log (obj2.objflag); // self-built Obj object
Prototype is too cumbersome to write and hard to remember. Generally, attributes and Methods common to many instances are fixed and cannot be changed. Therefore, we can use the initialization object method to write native links, I learned this idea from jQuery. The Code is as follows:
// Simplified prototype

Function Obj (id1, name1, teststring1)
{
This. id = id1;
This. name = name1;
This. teststring = teststring1;
This. sayHello = function ()
{
Console. log ('Id: '+ this. id + '@! @ Name: '+ this. name + '@! @ Teststring: '+ this. teststring );
}
}
Obj. prototype = {
Objflag: 'Self-built Obj object ',
ProSayHello: function (){
Console. log ('Hello World and Obj ');
}
};
Var obj1 = new Obj ('010 ', 'My Name is obj10', 'test obj10 ');
Var obj2 = new Obj ('011', 'My Name is obj11', 'test obj11 ');

Obj1.sayHello (); // id: 010 @! @ Name: My Name is obj10 @! @ Teststring: Test Obj10
Obj2.sayHello (); // id: 011 @! @ Name: My Name is obj11 @! @ Teststring: Test Obj11
Obj1.proSayHello (); // Hello World and Obj
Obj2.proSayHello (); // Hello World and Obj
Console. log (obj1.objflag); // self-built Obj object
Console. log (obj2.objflag); // self-built Obj object
Now, the upper part of the topic is finished. The upper part is mainly about usage and concept. In the lower part, I will analyze some principles and explain some odd phenomena.

Author: Summer forests

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.