Js model and encapsulation, Js model Encapsulation

Source: Internet
Author: User

Js model and encapsulation, Js model Encapsulation

A little bit of poor sharing. You are welcome to criticize and supplement it.

We often construct Json-format false data for our various components in Js. We can see the following code:

Var jsonResult = [{'name': 'ws ', 'age': '22'}, {'name': 'td', 'age ': '22'} // we regard jsonResult [x] as an object, where the attribute is naturally]; window. onload = function () {alert (jsonResult [0]. name );}

The object method is as follows:

Var jsonResult = [{'name': 'ws ', 'age': '22', 'speakfunc': function () {alert ('Hi, my name is ws ') ;},{ 'name': 'td', 'age': '22', 'speakfunc': function () {alert ('Hi my name is '+ jsonResult [1]. name) ;}} // we regard jsonResult [x] as an independent individual object]; window. onload = function () {jsonResult [0]. speakFunc (); jsonResult [1]. speakFunc ();}

 

The following describes the methods for readability and better reusability, including closures.

Var myUpStageClass = function () {var instance = {firstFunc: function () {// method name can be quoted without alert ('first method output');}, 'secondfunc ': function (param) {alert (param) ;}} return instance; // returns the closure object} var appObj = myUpStageClass (); // accepts the closure object, is it like instantiating a window. onload = function () {appObj. firstFunc (); appObj. secondFunc ('second method output ');}

We recommend that you encapsulate the JavaScript code we need with high reusability as the top-level JS of our project, and accept the closure object globally outside the closure and provide it to lower-layer calls.

 

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.