Reading Notes: JS design mode

Source: Internet
Author: User
<span id="Label3"></p><p><p>Process-oriented programming, object-oriented programming and functional programming<br>> Define a Class<br>Method 1:<br>function Anim () {<br><br>}</p></p><p><p>Anim.prototype.start = function () {..};<br>Anim.prototype.stop = function () {..};</p></p><p><p>Or<br>Method 2:<br>function Anim () {..}<br>Anim.prototype = {<br>Start:function () {..},<br>Stop:function () {..},<br>Constructor:anim<br>}</p></p><p><p>Or<br>Method 3:<br>visually, the entire class is defined in the Constructor.<br>function Anim () {<br>...<br>If (! Anim.prototype.version) {//assume that version is the method that this class must have<br>Anim.prototype.version = ' 1.0 ';<br>Anim.prototype.start = function () {..};<br>Anim.prototype.stop = function () {...};<br>}<br>}</p></p><p><p>New Anim (); The 1th time New is completed the definition of the prototype object</p></p><p><p>Or<br>Method 4:<br>The process of adding a method to a function prototype object is defined as a function, such as:<br>Function.prototype.method = function (name, Fn) {<br>this.prototype[name] = fn;<br>Return this; Makes it possible to Chain-call<br>}</p></p><p><p>It's no different from the 1th method.<br>function Anim () {...}<br>Anim.method (' start ', function () {.});<br>Anim.method (' stop ', function () {:});</p></p><p><p>> JS Data type: Original type number string Boolean null undefined, reference type Object (array, function, regexp, math, number, string, Boole An<br>Raw data types are passed by value; reference types are passed by reference (that is, reference addresses)<br>Data type Conversions:<br>ToString ();<br>parseint ();<br>Parsefloat ();<br>!! Number<br>Note the implicit type conversion of JS</p></p><p><p>The > function is a Class-a object that can be stored in a variable and can be passed as a parameter and can be returned as a function return Value.<br>Anonymous functions can fire a scope, without affecting the global environment, to achieve data encapsulation<br>(function () {<br>var foo = 10;<br>var bar = 2;<br>Alert (foo * bar);<br>})();</p></p><p><p>var result = (function (foo, Bar) {<br>return Foo * Bar<br>}) (20, 10);</p></p><p><p>JS has a function scope, and the scope of JS is the lexical scope (the function runs in the scope that defines it, not in the scope in which it is called)<br>The most interesting use of anonymous functions is to create closures.<br>Example of creating closures with anonymous functions:<br>var baz;<br>(function () {<br>var foo = 10;<br>var bar = 2;<br>Baz = function () {<br>return foo * bar;<br>}<br>})();<br>Baz (); 20</p></p><p><p>> JS objects are variable<br>/* class Person */<br>function Person (name, Age) {<br>THIS.name = name;<br>This.age = age;<br>}<br>Person.prototype = {<br>Getname:function () {reutn this.name},<br>Getage:function () {return this.age},<br>Constructor:person<br>}</p></p><p><p>/* instantiate the class */<br>var alice = new Person (' Alice ', 19);</p></p><p><p>/* Modify the class */<br>Person.prototype.geeting = function () {return ' Hi, ' + this.getname + '! '};</p></p><p><p>/* Modify the instance */<br>alice.displaygeeting = function () {<br>Alert (this.geeting ());<br>}</p></p><p><p>js, anything can be modified at run time</p></p><p><p>> Inheritance<br>Two types of inheritance paradigm of primitive inheritance and class-based inheritance</p></p><p><p>Benefits of using design patterns in js: maintainability, performance, programmer communication, cons: Complexity performance (some models have a negative impact on performance, some can improve Performance)</p></p><p><p>-----------------------------------<br>Interface<br>-----------------------------------<br>Interface: provides a means of explaining what an object should be<br>Assuming that a batch of objects implements the same interface, they can be treated the same even if they are unrelated to each other.<br>Such as: a batch of objects have implemented the comparable interface, then you can call Obj.compare (obj2);</p></p><p><p>Interfaces can tell programmers what methods are implemented in a class, and interfaces describe what features and actions a class has</p></p><p><p>The method of imitating interface in > js: annotation method, attribute check method, duck type distinguishing type</p></p><p><p>1. Annotation Method:<br>/*<br>Interface composite{<br>function Add (child);<br>function Remove (child);<br>function Getchild (index);<br>}</p></p><p><p>Interface formitem{<br>function Save ();<br>}<br>*/</p></p><p><p>var compositeform = function (id, method, action) {//implements Composite, FormItem<br>...<br>};</p></p><p><p>Implement the Composite interface<br>CompositeForm.prototype.add = function (child) {..};<br>CompositeForm.prototype.remove = function (child) {..};<br>CompositeForm.prototype.getChild = function (index) {.};</p></p><p><p>Implement the FormItem interface<br>CompositeForm.prototype.save = function () {...};</p></p><p><p>Rely on the programmer to consciously abide by the interface conventions, do not affect performance; but no error prompts</p></p><p><p>2. Property Check Method:</p></p><p><p>/*<br>Interface composite{<br>function Add (child);<br>function Remove (child);<br>function Getchild (index);<br>}</p></p><p><p>Interface formitem{<br>function Save ();<br>}<br>*/</p></p><p><p>var compositeform = function (id, method, Action) {<br>this.implementsinterfaces = [' Composite ', ' FormItem '];//claiming to have implemented which interfaces<br>...<br>}</p></p><p><p>function AddForm (forminstance) {//a method of invoking an instance<br>If (!implements (forminstance, ' Composite ', ' FormItem ')) {//check If the instance implements the specified interface<br>Throw new Error (' instance does not implement the required interfaces ');<br>}<br>...<br>}</p></p><p><p>Check that the required interface is found in an array of interfaces that the instance object claims to implement<br>~ ~ Check the incoming interface name, whether in the self-proclaimed interface array can be found<br>function Implements (object) {<br>For (var i=1; i<arguments.length; I++) {//traversal of incoming interfaces<br>var InterfaceName = argument[i];<br>var interfacefound = false;<br>for (var j = 0; J < object.implementsInterfaces.length; J + +) {<br>if (object.implementsinterfaces[j] = = Interfacename) {<br>Interfacefound = true;<br>Break<br>}<br>}<br>If (!interfacefound) {return false;}<br>}<br>Return true; No exits, all interfaces can be found<br>}</p></p><p><p>3. Duck Type: Walking quack is a duck<br>If an object has all methods with the same name as an interface-defined method, it is assumed that it implements this interface</p></p><p><p>/* class Interface */<br>var Composite = new Interface (' Composite ', [' add ', ' Remove ', ' getchild ']);<br>var FormItem = new Interface (' FormItem ', [' Save ']);</p></p><p><p>Class Compositeform<br>var compositeform = function (id, method, Action) {<br>...<br>}</p></p><p><p>function AddForm (forminstance) {<br>Ensureimplements (forminstance, Composite, FormItem);<br>...<br>}</p></p><p><p>Ensure that the class really implements the method of the interface definition, the disadvantage: the class does not declare which interfaces it implements</p></p><p><p>The better way is to combine the annotation method + Duck type distinguishing type such as:<br>Interfaces<br>var Composite = new Interface (' Composite ', [' add ', ' Remove ', ' getchild ']);<br>var FormItem = new Interface (' FormItem ', [' Save ']);</p></p><p><p>Class Compositeform<br>var compositeform = function (id, method, action) {//implements Composite, FormItem<br>...<br>}</p></p><p><p>function AddForm (forminstance) {<br>Ensureimplements (forminstance, Composite, FormItem);<br>...<br>}</p></p><p><p>/** class Interface **/<br>function Interface (name, Methods) {<br>If (arguments.length!== 2) {<br>Throw new Error (' expect 2 arguments ');<br>}<br>THIS.name = name;<br>This.methods = [];<br>If (methods.constructor!== array) {throw new Error (' expect an array for methods Param ')}<br>For (var i =0, len=methods.length; i<len; i++) {<br>If (typeof methods[i]!== ' string ') {<br>Throw new Error (' expect string value ');<br>}<br>This.methods.push (methods[i]);<br>}<br>}</p></p><p><p>/** Ensureimplements Method **/<br>function Ensureimplements (object) {<br>If (arguments.length < 2) {throw new Error (' expect arguments at least 2 ');}<br>For (var i=1, len=arguments.length; i<len; I++) {<br>var interface = Arguments[i];//traversal interface<br>If (interface.constructor!== Interface) {<br>Throw new Error (' expect this argument to be Interface instance ');<br>}<br>For (var j=0,mlen=interface.methods.length; j<mlen; j + +) {//method to traverse the interface<br>var method = interface.methods[j];<br>If (!object[method] | | typeof object[method]!== ' function ') {<br>Throws an exception if object has no method with the same name as the interface method<br>throw new Error (' not the method: ' +method);<br>}<br>}<br>}<br>}</p></p><p><p>The interface reduces the coupling between the objects, improves the flexibility of the code, does not require an inheritance relationship between the objects, as long as they implement the same interface, it can be treated equally.<br>The API is documented in the interface and can be used as a tool for programmer communication<br>Scenario: for externally provided service APIs such as search map messages, Create a Interface object and interface check for each object received, such as:<br>var dynamicmap = new Interface (' dynamicmap ', [' centeronpoint ', ' zoom ', ' Draw ']);</p></p><p><p>function Displayroute (mapinstance) {///own instance method is used as interface to ensure that the incoming instances do have these methods<br>Ensureimplements (mapinstance, dynamicmap);<br>Mapinstance.centeronpoint (12,34);<br>Mapinstance.zoom (3);<br>Mapinstance.draw ();<br>...<br>}</p></p><p><p>Whether you need to use an interface for checking depends on the size of the project and the need to do the Checking.<br>It is guaranteed and flexible to have an interface check on incoming objects (whether to implement an interface) than to do class checking (whether a class).</p></p><p><p>Interface-dependent Design Patterns<br>Factory mode, combination mode, Decorator mode, Command mode</p></p><p><p>>> Encapsulation and information hiding<br>Creating a private member for an object is one of the most basic and useful features of an object-oriented language. Encapsulation is the cornerstone of Object-oriented.<br>The encapsulation in JS is implemented by a closure package.<br>Information hiding helps to reduce the dependency between functional modules, only the results are needed, and no specific internal implementations need to be known.<br>Encapsulation: hides the Object's internal data and implementation details, many object-oriented languages declare the property or method as hidden (private) in the keyword, and private in Java<br>, JS with closed package</p></p><p><p>Encapsulation: hides the data inside the object and the implementation details, and only accesses the Object's data in a defined Way.</p></p><p><p>>> basic patterns for creating objects</p></p><p><p>> Portal Large open Object (all properties of an object are public members)<br>var book = function (isbn, title, author) {<br>if (ISBN = = undefined) throw new Error (' ISBN is required '); Not checking ISBN is correct, may affect database retrieval and display book information<br>to = if (!this.checkisbn (isbn)) throw new Error (' ISBN is invalid ');<br>THIS.ISBN = isbn;<br>this.title = Title | | ' No title specified ';<br>This.author = Author | | ' No author specified ';<br>}<br>Book.prototype.display = function () {<br>...//generate elements that display book information<br>}<br>BOOK.PROTOTYPE.CHECKISBN = function () {<br>...<br>}</p></p><p>---------<br>Instead: access the properties of the Portal wide open object only through Getter,setter<br>var Publication = new Interface (' Publication ', [' getisbn ', ' setisbn ', ' getTitle ', ' settitle ', ' getauthor ', ' Setauthor ', ' Display ']);<br>var book = function (isbn, title, author) {<br>THIS.SETISBN (isbn);<br>This.settitle (title);<br>This.setauthor (author);<br>}<br>Book.prototype = {<br>constructor:book,<br>Getisbn:function () {return this.isbn},<br>Setisbn:function (isbn) {if (!this.checkisbn (isbn)) {throw new Error (' Invalid ISBN ')}else{this.isbn = isbn}},<br>Gettitle:function () {return this.title},<br>Settitle:function (title) {return this.title = Title | | ' No specified title '},<br>Getauthor:function () {return this.author},<br>Setauthor:function (Author) {return this.author = Author | | ' No specified Author '},<br>Display:function () {...},<br>Checkisbn:function () {..}<br>}<br>But<br>Book = The new book (' 0-234-234-034-9 ', ' Something of Life ', ' Kitty ');<br>BOOK.ISBN = ' 0-000-000-000-2 '; The properties of an instance object can be modified Arbitrarily.<br>Advantages: simple, Easy to understand<br>Cons: all properties and methods exposed cannot protect internal data, getter,setter increase the amount of code</p><p><p>> distinguish a private member with a naming convention (the property name plus _ prefix indicates that it is private, such as: _name = ' Kitty book ')<br>var book = function (isbn, title, author) {<br>THIS.SETISBN (isbn);<br>This.settitle (title);<br>This.setauthor (author);<br>}<br>Book.prototype = {<br>constructor:book,<br>Getisbn:function () {return this._isbn},<br>Setisbn:function (isbn) {if (!this.checkisbn (isbn)) {throw new Error (' Invalid ISBN ')}else{this._isbn = isbn}},<br>Gettitle:function () {return this._title},<br>Settitle:function (title) {return this._title = Title | | ' No specified title '},<br>Getauthor:function () {return this._author},<br>Setauthor:function (Author) {return this._author = Author | | ' No specified Author '},<br>Display:function () {...},<br>Checkisbn:function () {..}<br>}</p></p><p><p>> scoped nested functions and closures<br>JS has only function scopes and lexical scopes, and functions are run at the scope in which they are defined, rather than the scope in which they are called.<br>Returning an inline function is a common way to create Closures.</p></p><p><p>var book = function (newisbn, newtitle, newauthor) {//implements Publication<br>var isbn, title, author; Private properties<br>function Checkisbn (isbn) {...}//private method<br>THIS.GETISBN = function () {return isbn}; Privileged methods<br>THIS.SETISBN = function (newisbn) {if (checkisbn (newisbn)) ISBN = newisbn;};//privileged method<br>This.gettitle =..<br>This.settitle =..<br>This.getauthor =..<br>This.setauthor =..</p></p><p><p>Initializing object private Data<br>THIS.SETISBN (newisbn);<br>This.settitle (newtitle);<br>This.setauthor (newauthor);<br>}</p></p><p><p>Book.prototype = {<br>construcor:book,<br>Display:function () {:}//public method, non-privileged method<br>}</p></p><p><p></p></p></span>

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.