On JavaScript Object-oriented

Source: Internet
Author: User

Two of the programming patterns we use

pop--process-oriented programming (Process-oriented programming)

Process-oriented programming is a programming method of thinking and organizing based on function, which emphasizes that the process of data processing and processing in the system is mainly based on function or process as the basic organization of program, and the system function is composed of a set of related process and function sequences. Process-oriented emphasis is on functionality (processing), where data is only available as input and output. This process of thought is a very simple and universal ideas and methods, many human activities are such organizational models, such as factory production, corporate services. The process takes the process of data processing as the main line, ignoring the process of owning, boundary and environment, confusing the service function and self-function (for example, the person can cut down the tree, this is a service function, there is input and output; it can be provided to the outside, while walking, it is self-function, no input and no output), The difference between the external environment and the internal organization, as well as the environmental data and the raw material data. In terms of thinking, the process is more emphasis on detail, ignoring the integrity and the boundary, but this is very much in the real world, because in the real world, this process is not isolated, but belongs to an object, therefore, the process of orientation, although reflects the real world and one aspect (function), But it is impossible to simulate or represent the real world more vividly. For example, the following wording:

function  A () {}  function  B () {   A ();}

Feeling independent of each other

oop--OO Programming (Object Oriented programming)

The world is made up of objects, so the object-oriented way of thinking is closer to the real world, and the organization of object-oriented programming is closer to the real world. Object-oriented objects, the internal organization of the object and the external environment, distinguish the internal attribute data of the characterization object from the outside, its behavior and properties constitute a whole, and the system function is represented as a series of interactions between the series of objects, can more vividly simulate or express the real world. In a programming organization, the properties and methods of an object are no longer stored separately as a process, but as a whole (the final implementation of the program is still separate, but this is only a physical implementation and does not affect the two parts of the object as a whole). Therefore, it has better encapsulation and security (characterization of internal attribute data needs to be accessed through the provided method of the object). Object-oriented emphasizes wholeness, so object-oriented and process-oriented can be complementary in many ways. At the same time, due to the introduction of object inheritance and polymorphism technology, object-oriented has stronger and more concise expression ability to the real world. This enhances the organization, reusability, and flexibility of programming. For example, the following wording:

var   obj={  default:{},  config:{},  init:function () {this    . A ();    This. B ();  },  a:function () {      this.config.name= ' A ';  },  b:function () {    this.config.name= ' B ';  }}

This seems to be a bit oo feeling, the properties and methods encapsulated in an object. The object-oriented development model is a model that is becoming popular and widely popularized by the developers themselves.

JavaScript is an object-based language, but it is not a real object-oriented programming (OOP) language, and the properties of objects are in the form of key-value pairs, which is what we call a data dictionary. The object's properties and methods are encapsulated in an object, typically in four ways: primitive object, constructor, prototype mode, constructor and prototype blending mode. I personally think that object-oriented writing makes the system more maintainable, extensible, reusable, and configurable, and the function module also makes people feel at a glance.

Here's a look at the package, inheritance, and polymorphism of JavaScript's corresponding OOP

    • Encapsulation of Objects

(1) object literal or Instanced object pattern

var Obj = {    Id: ',    Width: ',    Height: ',    init:function () {    },    eventsbind:function () {    },    renderview:function () {    }}

Or

Var obj=new Object ();

Obj.id= ";

Obj. Renderview ....

This packaging method is simple, the most common one mode, concise and clear, suitable for the simple package. These two ways of writing, are recommended in the literal way.

(2) Constructor mode

function Myplugin (name, pwd) {    this.name = name;    This.pwd = pwd;    This. Init = function () {    };    This.renderview = function () {    };    This.bindevent = function () {    }}

This way is similar to C # constructor, each instantiation, all the elements and methods are recreated, re-allocating memory, the disadvantage is that the public approach to different addresses when instantiated, resulting in unnecessary waste, poor performance, methods should be shared, the following mixed mode will be discussed.

(3) prototype prototype

var myplugin = function () {}myplugin.prototype = {    obj: {        name: ' AAAAA '    },    init:function () {    } ,    renderview:function () {    },    bindevent:function () {    }}

The feature of this approach is that all methods on the prototype chain are shared and point to the same address. It is important to note that if the previous attribute of the prototype chain corresponds to an object, there is a problem that assigning a property to the object within an instance object will affect the other instance object.

var a=new myplugin ();

var b= new Myplugin ();

A.obj.name= ' BBBBBBBB '

This will change the name value of the Obj object in B. The reason is that obj here is a reference type, a.obj and B.obj point to the same address, and if it is a value type there is no such problem

(4) constructor and prototype blending modes

The meaning of this pattern is that when instantiated, the attributes are kept separate from each other, and only the methods are shared. This is recommended in the case of encapsulation. The disadvantages of the constructors we have just described and the shortcomings of the prototype pattern are improved here.

var myplugin = function (name) {    this.name = name;} Myplugin.prototype = {    show:function () {        Console.log (this.name);    }}

(5) Other wording

var myplugin = function (config) {    var fn1 = function () {    }    var fn2 = function () {    }    return {        TEST1:FN1,        test2:fn2    }}

Or

var myplugin = function (config) {    var obj = new Object ();    OBJ.FN1 = function () {    }    obj.fn2 = function () {    }    return obj;}    

Just now we mentioned that the method address of the object after the constructor pattern instantiation is not the same, while the prototype mode, the address points to a consistent argument.

Let's take a look:

var   funcdemo=function (name) {}funcdemo.prototype.init=function () {}var  a=new  funcdemo (' aaa '); var  b=new  funcdemo (' BBB '); Console.log (A.init===b.init);

The result of the output is true.

Take a look at the constructor:

var   funcdemo=function (name) {this     . Init=function () {     }}var  a=new  funcdemo (' aaa '); var  b=new  Funcdemo (' BBB '); Console.log ( A.init===b.init);

The result of the output is false.

    • Inheritance of objects

1.call, apply

var Funca = function () {    this.show = function () {        console.log (' Funca ');}    } var FUNCB = function () {    funca.call (this);} var B = new FUNCB (); B.show ();

Here Funca.call (this), which is equivalent to being executed inside the FUNB.

This.show=function () {

Console.log (' Funca ');

}

While the current scope is within FUNCB, this refers to the instantiated object of Funb, which assigns the show method to the instantiated object of FUNCB.

It is important to note that if FUNCB () is executed directly, then the current scope is window, which is equivalent to assigning the Show method to window. Equivalent to

Window.show==function () {     console.log (' Funca ');}

2. Prototype inheritance

var Funca = function () {    this.show = function () {        console.log (' Funca ');}    } var FUNCB = function () {}funcb.prototype = new Funca (); var b = new FUNCB (); B.show ();

This sentence funcb.prototype=new Funca ();

It's equivalent to pointing Funb's prototype to an example of Funca.

Equivalent to

FUNCB. prototype={  show:function () {     console.log (' Funca ');}}

We can write a function to implement inheritance

var extend = function (FN, NEWFN) {var F = function () {}; F.prototype = Fn.prototype;newfn.prototype = new F (); newfn.prototype.constructor = Newfn;newfn.prototype.superclass = Fn.prototype}

3. Property Copy

Let's first implement the code for the property copy:

var deepcopy = function (newobj, obj) {for    (var prop in obj) {        if (Obj.hasownproperty (prop))        {            var item = OB J[prop];            if (Object.prototype.toString.call (item) = = ' [Object Object] ')            {                Newobj[prop] = {};                Arguments.callee (Newobj[prop], item);            }             else if (Object.prototype.toString.call (item) = = ' [Object Array] ')            {                Newobj[prop] = [];                Arguments.callee (Newobj[prop], item);            }             else                Newobj[prop] = Item;        }    }    return newobj;}

Then assign the attributes in the A object to the B object:

var A = {    obj: {        name: ' AAAA '    },    Arr: [        {            name: ' AAAA '        },        {            name: ' BBBB '        }    ]} var b = {    name: ' bbbbbbbbbb '}deepcopy (b, A)
    • The polymorphism of the object

As in other languages, first define a base class, JS does not exist the concept of class, here I just analogy.

var   baseclass=function () {         this.init=function () {               this.test.apply (this,arguments);}         }

The execution of Init here is actually the test method that executes the subclass

We'll define Class A, Class B.

var  a=function () {         this.test=function () {                   alert (' aaaaaaaaaa ');}         } var  b=function () {         this.test=function () {                   alert (' bbbbbbbbbbbbb ');}         }

Then the prototype of Class A, Class B, points to an instance of BaseClass, which is what we just said about prototype inheritance.

  A.prototype=new BaseClass ();  B.prototype=new BaseClass ();

Finally we instantiate

var  a=new  A (); A.init (); var  b=new  B (); B.init ();

Output ' aaaaaaaaaa ' separately, ' bbbbbbbbbbbbb '

We realized that the multi-state and strongly-typed language of JS is different, it is not so intuitive, because the strong type of language is mostly through the abstract class or interface declaration method, and then through the subclass implementation, when invoking the method is actually instantiated abstract class or interface, point to the child class object instance. And our implementation here is actually the implementation of calling a subclass on the parent class declaration method through the parent class declaration method.

Js Object-oriented this part of the thing I am also roughly speaking, explain the inappropriate or imperfect place, please also specify. If you are interested in exchanging study, please see the top corner, join my QQ technology group 207058575.

On JavaScript Object-oriented

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.