The idea of JavaScript programming with light pull

Source: Internet
Author: User
Tags function prototype regex replace

First, object-oriented-ood

Although JS object-oriented programming idea has been talk about, but for the sake of the integrity of the article, I still add it in, try to speak in a different way (although there is no egg different).

1, object-oriented, first have to have the concept of class, there is no class can not be made out of the object, but there is no class in JavaScript only the function of gratitude, the capital letter named function as the constructor of the creation of the object, the function name as a class, then you can new an object

1.1 Parameterless Function people () {}var p = new People ();//javascript is an explanatory language, run-time compiled, so we have something to do with the property. P.name = ' Hannimei '; Console.log (p.name);//2.2 Some parameter function Student (name, age) {    this.name = name;    This.age = age;    This.say = function () {        return saywhat ();    }
Private functions
function Saywhat () {
Return this.name+ ': Say what? ';
} return this; var s = new Student (' Lily '); Console.log (s.name); Console.log (S.say ());//2.3 A dozen factoryfunction Factory (name,age) { var obj = new Object (); Obj.name = name; Obj.age = age; Obj.say = function () { return obj.name+ ': Say what? '; } return obj;} var o = new Factory (' Factory ', 1); Console.log (O.say ());//2.4 object literal creation object var ob = {Name: "literal", age:18};//of course there are also string literals, array literals these var str = ' Hello javascript! '; var arr = [1, 2, 3, 4, 5];

2, then have the class, object-oriented also can not be less than the characteristics of inheritance, JS inheritance in various ways, through the function of the prototype chain is the most common

Born with skill is life, if later want to cultivate skills, what to do, direct point out is good, if you do not want to cultivate to be born to bring, that will have to say prototype.

function Teacher (schoolname) {            this.schoolname = schoolname;            return this;        } var t = new Teacher (' 2b1 in ');

When you create the Teacher function object T, the __proto__ of T points to an object, which is actually the prototype of the function (why?). Listen to me slowly down the road), this object has two properties, constructor defines the teacher function to create it, __proto__ continue to point up to object, through the structure of the object two fork tree, it identifies how the object came and born with what skills.

Then we want to bring our own skills in the background by adding T's __proto__ pointing to the object default skill

From Teacher's Watch chart we see two key properties, one is its function prototype prototype, the test learns that this thing and the __proto__ point to the same object, then we also know the function of another __proto__ Is the prototype of the function that points to its parent, and ultimately the prototype of the object

After the above conditioning, we finally understand the innate inheritance, the day after tomorrow, the true meaning of the sentence; try to relive this sentence

2.1 Add Attribute function Teacher (schoolname) {    this.schoolname = Schoolname directly to prototype;    return this;} Teacher.prototype.age = 18; Teacher.prototype.jiangke = function () {    return ' The teacher began to lecture ';} var t = new Teacher (' 2b1 '); Console.log (t.age); Console.log (t.schoolname); Console.log (T.jiangke ());//2.2 Through prototype inheritance, prototype points to an object, so we inherit from the parent class new out of the objects will be able to//This code throws the long-winded function people (name) {    this.name = name;    This.say = function () {        return this.name + ': Say what? ';    }    return this;} function Student (name) {    this.name = name;} Student.prototype = new People (Student.name); var s = new Student (' Ah Amitabha pill '); Console.log (S.say ());

Second, data-oriented-DOP

1. Preliminary study

JS for data programming This concept is Ali what forum to put forward, in simple terms, we do not bother to use JS to manipulate DOM elements, by directly to the data assignment modification, and then replace to the HTML template, and finally directly call innerHTML display; For example, although not appropriate is not complete, but the words are not rough, it is only used to illustrate the problem

This is our humble shopping cart, there are two kinds of fruit and the number to buy, through +/-Modified number

<div id= "Gwcid" >    <p> oranges: <input type= "Number" value= "1"/><input type= "button" value= "+" onclick= "ChangeEvent (' orange ');"/></p>    <p> Apple: <input type= "Number" value= "1"/><input Type= "button" value= "+" onclick= "changeevent (' apple ');"/></p></div>

In the traditional way, we manipulate the DOM and then modify its value, but when it comes to data programming, you need to have a JSON model, then an HTML view, relace the value of the property after the operation to the view, and finally innerHTML. The benefits of this versatile programming approach are naturally self-evident, and it is essential to deal with big data at the speed of browser rendering.

var fruits = {orange:1, apple:1};
Templates can be read in HTML, here for the convenience of var TPL = ' <p> Orange: <input type= "number" value= "<%orange%>"/><input type= " Button "value=" + "onclick=" changeevent (\ ' orange\ '); " /></p><p> Apple: <input type= "number" value= "<%apple%>"/><input type= "button" value= "+" onclick= "ChangeEvent (\ ' apple\ ');" /></p> '; function changeevent (name) { //Operation data Fruits[name] + = 1; Replace value var result = TPL. SetValue (fruits); InnerHTML document.getElementById (' Gwcid '). InnerHTML = result;} String.prototype.SetValue = function (JSON) { //regex replace return This.replace (/<%\w+%>?/gi, function (matchs) { var str = json[matchs.replace (/<%|%>/g, "")]; return str = = "undefined"? "": str; });

2. Start and end

After the above example, I believe that the JS template engine What we also end it, at least now all kinds of template engine I do not use too much, the official introduction of the words are too lazy to post out

The trend, now back-end many of the core of the idea of MVC, Dependency injection, modularity, etc. have been applied to the previous paragraph, and even native's MVVM thought all moved over, and here, presumably you have guessed what to say next--angularjs, here to learn the main document, The theory of thought is too lazy to post.

2.1 Expression

2.2 ng-

<!--Ng-app: Initialize the ANGULARJS application; Ng-init: initializes the application data. --><div ng-init= "word= '" > Hello {{word}}</div><!--ng-model: Bind element values (such as input field values) to the application--Enter: <input type= "text" ng-model= "input"/> You entered:{{input}}<!--ng-show: Verify that Ture--><p "True" is not displayed by returning ng-show= > can see </p><p ng-show= "false" > Invisible </p><p ng-show= "1=1" > expression established you can see </p><form action = "/" method= "POST" ng-app= "" Name= "Form1" > Email:<input type= "Email" name= "address" ng-model= "email"/> &lt , span ng-show= "form1.address. $error. Email" > Enter a valid mailbox </span> <ul> <li> field content is legitimate: {{Form1.addres S. $valid}}</li> <li> The form is filled in: {{form1.address. $dirty}}</li> <li> field contents are illegal: {{Form1.add ress. $invalid}}</li> <li> Whether to touch the screen: {{form1.address. $touched}}</li> <li> Whether the record is not filled in: {{Form1 . address. $pristine}}</li> </ul></form><!--ng-disabled: Not available--><button ng-disabled= " True "&Gt;!</button><!--ng-hide: Visible--><p ng-hide= "false" > can see </p><!-- Ng-bind: The value of the binding element innertext--><div ng-init= "quantity=3;cost=5" > Price: <span ng-bind= "Quantity*cost" ></ Span></div><div ng-init= "nums2=[10,20,30" "> <p ng-bind=" nums2[1] "></p></div>< !--Ng-click: Event--><div ng-init= "count=0;" > count:{{count}} <br/><button ng-click= "count=count+1" >+1</button></div><!-- Ng-repeat: Circular instruction--><div ng-init= "citys=[{name: ' Beijing ', Val:1},{name: ' Shanghai ', val:2},{name: ' Guangzhou ', Val:3}]" > < select> <option ng-repeat= "x in Citys" ng-bind= "X.name" value= "{{x.val}}" ></option> &LT;/SELECT&G t;</div><!--ng-include: Contains HTML content--><div ng-include= "' 05service.html '" ></div><!-- Custom Directives--><!--label--><runoob-directive></runoob-directive><!--Properties--><div runoob-directive></div><!--class name--><div class= "Runoob-directive"></div><script type= "Text/javascript" > var app = angular.module ("myApp", []);             App.directive ("Runoobdirective", function () {return {//restrict: "E", E is only for element invocation, A is only for attribute invocation, C is only called for class name, M is only a comment call    Replace:true, when commented for M, is true template: "

    2.3 scope

<!--the Ng-controller directive defines the application controller, and in the controller adds the attribute to $scope, the view can pass in the past using--><div ng-app= "myApp" > <div Ng-controller= "Ctrl" > {{name}}<br/> {say ()}} <br/> {{$root. genname}} </div> <div ng-controller= "Ctrl1" > {{$root. Genname}} &lt ;/div></div><div id= "Div2" ng-app= "myApp2" ng-controller= "Ctrl2" > {{name}}</div><script Type= "Text/javascript" > var app = angular.module (' myApp ', []);        ' [] ' is used to create dependencies, and no words to continue using the previously created App.controller (' Ctrl ', function ($scope) {$scope. Name = ' scope ';    $scope. Say = function () {return ' Hello,sister '};    }); Rootscope root scopes, which function throughout the app, can use App.controller (' Ctrl1 ', function ($scope, $rootScope) {$rootScope) in each controller.    . Genname = ' root scope ';    }) var app2 = angular.module (' myApp2 ', []);    App2.controller (' Ctrl2 ', function ($scope) {$scope. Name = ' another scope '; })//Start the second app manually, clear the scope Oh Angular.bootstrap (document.getElementbyid (' Div2 '), [' myApp2 ']) </script> 

2.4 Filter

<!--currency format numbers as currency formats. Filter selects a subset from the array item. The lowercase formatted string is lowercase. Order by to arrange an array based on an expression. Uppercase formatted string is uppercase. --><div ng-app= "" ng-init= "name= ' Lily '; citys=[{name: ' Beijing ', Val:1},{name: ' Shanghai ', val:2},{name: ' Guangzhou ', Val:3}]" >    {{Name|uppercase}}  <!--expression--    <ul>        <li ng-repeat= "C in citys|filter:inp| ORDER BY: ' Val ' >{{c.name}}</li>  <!--directive Filter--    </ul>    <input type= "text" Ng-model= "INP" >  <!--input filter li--></div>

2.5 Service

<div ng-app= "MYAPP" ng-controller= "Ctrl" >    current url:{{currenturl}}<br/>    GET request JSON data: {{Jsondata}}    Custom Service: {{myservice}}</div><script type= "text/javascript" >    //Custom Service    angular.module (' myApp ', []). Service (' MyService ', function () {        this.tostartupper = function (str) {            return str.substring (0, 1). toUpperCase () + str.substring (1);};    });    Angular.module (' myApp '). Controller (' Ctrl ', function ($scope, $timeout, $location, $http, MyService) {        $ Scope.currenturl = $location. Absurl ();  $location the URL address of the current page        $timeout (function () {  //$timeout equivalent to window.settimeout;$ Interval equivalent to Window.setinterval            console.log (' timeout executed ');        }, 2000);
HTTP request XMLHttpRequest $http. Get (' Json.txt '). Success (function (response) {$scope. Jsondata = response;}); $scope. MyService = myservice.tostartupper (' service '); }); </script>

2.6 API

<div ng-app= "MyApp" ng-controller= "Ctrl" >    whether it is a string: {{isstr}}<br/>    is a number: {{isnum}}<br/> To    Uppercase is: {{strtoupper}}<br/></div><script type= "Text/javascript" >    angular.module (' MyApp ', []). Controller (' Ctrl ', function ($scope) {        $scope. str = ' SDFSDF ';        $scope. Isstr = angular.isstring ($scope. str);        $scope. Strtoupper = Angular.uppercase ($scope. str);        $scope. Isnum = Angular.isnumber ($scope. str);    }); </script>

2.7 Animate

<!--nganimate model you can add or remove class. The nganimate model does not animate HTML elements, but nganimate monitors events like hidden HTML elements, and if an event occurs Nganimate uses a predefined class to animate the HTML element. --><input type= "checkbox" ng-model= "MyCheck" > Point I hide div<!--Add/Remove class instructions:        ng-show        ng-hide        Ng-class        ng-view        ng-include        ng-repeat        ng-if        ng-switch    ng-show and ng-hide instructions for adding or removing ng-hide Class value    Other directives add the Ng-enter class to the DOM, and removing the DOM adds the Ng-leave property    when the HTML element position changes, the ng-repeat instruction can also add Ng-move class     --&G T;<div ng-hide= "MyCheck" ></div><script type= "Text/javascript" >    var app = Angular.module (' MyApp ', [' nganimate ']);</script>

2.8 DI

var app = Angular.module (' MyApp ', []);//Inject Valueapp.value (' Defaultval ', 0);//factory inject serviceapp.factory (' Sumservice ', function () {    var factory = {};    Factory.sum = function (A, b) {        return a + b    }    return factory;}); /Custom Computeserver Service App.service (' Computeserver ', function (sumservice) {    this.sum = function (A, b) {        return Sumservice.sum (A, b);    }; /providerapp.config (function ($provider) {    $provider. Provider (' Sumservice ', function () {this        . $get = function () {            var factory = {};            Factory.sum = function (A, b) {                return a + b;            }            return factory;}    ); /CONSTANT constant Configuration app.constant (' Save ', ' false ');//injected Valueapp.controller (' Ctrl ', function ($scope, defaultval) {    $ Scope.defaultval = Defaultval;});

2.9 route

<body ng-app= "MyApp" ><ul> <li><a href= "#/" > Home </a></li> <li><a href= "#/ Product > Products </a></li> <li><a href= "#/about" > About </a></li></ul><div Ng-view></div><script type= "Text/javascript" >//Add route dependent angular.module (' MyApp ', [' Ngroute '])///  $routeProvider. When (URL, {//template:string, insert simple HTML content in Ng-view//templateurl:string, Templateurl    Inserts an HTML template file//controller:string, function or array, function, string, or array type, which executes the controller function on the current template, generating a new scope.    Controlleras:string, String type, specifying an alias for the controller.    Redirectto:string, function, redirect address//Resolve:object<key, function> Specify other modules//} that the current controller depends on); . config ([' $routeProvider ', function ($routeProvider) {//$routeProvider used to define a routing rule $routeProvider. When ('/', {tem                      PLATE: ' This is home ')//$routeProvider. The first parameter of the When function is a URL or url regular rule, and the second parameter is a routing configuration object.. When ('/product ', {Template: ' This is a product '}). When ('/about ', {Template: ' This is about us '})    . Otherwise ({redirectto: '/'}); }]);</script></body>

Third, facing H5

HTML5 to the force of the place, is nothing but a lot of JavaScript API, like the previous want to modify the URL parameters do not jump to do the logo, only with #, with the pushstata hehe; or do Webim polling server, now Windows server12+ WebSocket directly to get up (or with signalr really point, loaded force also no one believe), of course, whether it is a local database or websocket more or strong canvas API, etc. too much, in fact, not as Queryselector, Queryselectorall This kind of API to the reality (using the jquery selector is probably the way you think)

Then the problem comes, both want to write a set of code, and want to use H5 new API, and then the trend is out of the current, then need to be compatible with IE8 and under, for them to implement H5 these common API is good Caesar

Thought has come out, but the prototype has not yet followed, although very simple, but I still have the cheek to write

<input type= "text" id= "inputID" name= "name" value= "None"/><script type= "Text/javascript" >    if (! Window.localstorage) {        document.write (' <script src= "xxx.js" ><\/script> ");        document.write (' <script src= ' jquery-1.9.1.js ' ><\/script> ');        (function (d) {        //    d.query = function (selector) {        //        return $ (selector) [0];    }        //    Element.prototype.addEvent = function (types, fn) {        //        return $ (this). bind (types, fn) ;    }        //}) (document);    }    Window.onload = function () {        var obj = document.query (' #inputid ');        Console.log (obj.value);        Obj.addevent (' Change ', function () {            console.log (this.value);        })    }; </script>

Write more rotten, please do not reprint: http://www.cnblogs.com/NotAnEmpty/p/5462268.html

The idea of JavaScript programming with light pull

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.