In-depth JavaScript Object creation details

Source: Internet
Author: User
After studying javascript in depth recently, some individuals will: Object-oriented programming is efficient and flexible.

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.

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:

  1. Object
  2. Through Constructor
  3. Object initialization

1. Build an Object using the Object. The Code is as follows:

// Directly use the Object to create 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 objobj ['sayhel'] (); // id: 001 @! @ Name: My name is obj @! @ Teststring: Test objvar str = 'sayhel'; 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. We can place variables 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 the Object 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 Obj2obj ['sayhello'] (); // id: 002 @! @ Name: My Name is obj2 @! @ Teststring: Test Obj2var str = 'sayhel'; 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.

2. Through Constructors

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 the object 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 Obj3obj ['sayhello'] (); // id: 003 @! @ Name: My Name is obj3 @! @ Teststring: Test Obj3var str = 'sayhel'; 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:

// Thoroughly analyze the constring1 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: undefinedwindow. sayHello (); // id: undefined @! @ Name :@! @ Teststring: undefinedobj. 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 Obj5window. sayHello (); // id: 005 @! @ Name: My Name is obj5 @! @ Teststring: Test Obj5console. log (id); // 005console. log (name); // My Name is obj5console. log (teststring); // Test Obj5console. log (window. id); // 005console. log (window. name); // My Name is obj5console. 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. The creation of objects 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;
  3. 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 of function 1 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 Obj6window. sayHello (); // id: 006 @! @ Name: My Name is obj6 @! @ Teststring: Test Obj6console. log (id); // 006console. log (name); // My Name is obj6console. log (teststring); // Test Obj6console. log (window. id); // 006console. log (window. name); // My Name is obj6console. 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 of 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 ('20170', 'initobj0', 'test innerobj0');} var outObj = new OuterObj ('007 ', 'My Name is obj7 ', 'test obj7'); outObj. sayHello (); // id: 007 @! @ Name: My Name is obj7 @! @ Teststring: Test Obj7sayHello (); // window. sayHello (); // id: 102 @! @ Name: InnerObj0 @! @ Teststring: Test InnerObj0console. log (id); // 102console. log (name); // InnerObj0console. 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 Obj8obj ['sayhello'] (); // id: 008 @! @ Name: My Name is obj8 @! @ Teststring: Test Obj8var str = 'sayhel'; 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 = "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. Class attributes and Methods: object initialization can be considered as class attributes and methods. This definition is widely used in jQuery;
  2. Properties or methods of an object: Construct an object using constructor. The attributes and Methods pointed to by this pointer belong to the object;
  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 mode 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 Obj8obj2. sayHello (); // id: 009 @! @ Name: My Name is obj9 @! @ Teststring: Test Obj9obj1. proSayHello (); // Hello World and Objobj2.proSayHello (); // Hello World and Objconsole. 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 mode 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 Obj10obj2. sayHello (); // id: 011 @! @ Name: My Name is obj11 @! @ Teststring: Test Obj11obj1. proSayHello (); // Hello World and Objobj2.proSayHello (); // Hello World and Objconsole. log (obj1.objflag); // self-built Obj object console. log (obj2.objflag); // self-built Obj object

This article is available at http://www.nowamagic.net/librarys/veda/detail/355.

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.