JavaScript oriented[Exploring Object-oriented JavaScript advanced language features]

Source: Internet
Author: User
Tags closure object serialization

JavaScript oriented

Explore object-oriented JavaScript advanced language features

Prologue.  JavaScript Introduce1. Jsabstract

JavaScript is a scripting language developed by Netscape Company engineer Brendan Eich, which has been popularized and popular, compatible with ECMA-262 standards, and is now used to describe HTML Web page behavior. (Front-end verification, detection, response, triggering, control and other dynamic behavior)

Knowledge Tree

2. About Document

This article covers the concepts of JavaScript overview, Object type System, prototype chain, scope chain and context this, closures, namespaces, and object-oriented high-level language feature applications.

JavaScript knowledge points are complex and personal ability and learning time is limited, hope to get more encouragement and inspiration.

Chapter one.  Type Family1. That's all Object things?

From an object-oriented perspective, JS does everything. But JS is a functional programming, from a process-oriented perspective can be understood as all functions, which may be the charm of JavaScript. This article is called oriented JavaScript and tends to be understood from an object-oriented perspective.

How to understand "everything is the object". In general, we will explain from the object constructor and prototype chain, this article has a detailed overview, this is not a preliminary discussion.

2. Begin from GLOBAL

Here we start with JS's most special built-in object, Global.

Introduced

Global is one of two built-in objects in the ECMASCRIPT5 specification that represents a global object.

Role

Any properties and methods that are not part of JavaScript's other objects belong to global.

Realize

JavaScript does not have a clear implementation of it. The browser implements global as part of the Host object window.

The starting stage of Jsengine is to instantiate a Window object.

This also explains (this = = = window) = = true;

Property

Pre-defined objects

Object Array Function Boolean String number Date RegExp Error evalerror rangeerror referenceerror syntaxerror TypeError UR Ierror (constructor for function prototypes)

Global Properties

Undefined NaN Infinity ...

Global functions

Encode and Decode

decodeURI ()/decodeuricomponent ()/encodeuri ()/

encodeURIComponent ()/escape ()/unescape ()

Transformation

GetClass ()/number ()/string ()/parsefloat ()/parseint ()

Judge

Isfinite ()/isnan ()

Perform

Eval ()

User Defined

such as var _temp_val = {}; Window._temp_val = {}; global variable confusion problem

Tips: Global properties can be used directly without [window.] Object, except that the user-defined attribute cannot delete

When the JS engine starts and instantiates the Window object, the JS native object and the browser object are all placed in the window as predefined objects.

When we need to create a new object, the object prototype will be built based on these predefined objects first.

throw a little chestnut : (Here are some examples of constructors and prototype chains that are useful for grooming later chapters.) )

var window.namespacea = [];//declaration namespace

NAMESPACEA.A = {...};//declaration function, JS engine throws A.prototype to heap memory when loading

var a = Object.create (a.prototype,{... args});

JS Engine behavior :

Object () = window. Object.prototype.constructor;//object constructor function

Function () = window. Function.prototype.constructor;//function constructor function

A () = Window.namespacea.a.prototype.constructor; A constructor

A = new A ({... args});//Instantiate reference A with a object as a prototype

A.[[prototype]] = A.prototype;

3. We are Family

The diagram summarizes and references the ECMASCRIPT5 specification, if any errors are indicated.

For some of the objects, refer to the "http://www.w3school.com.cn/jsref/index.asp" tutorial

Chapter. User Object

This chapter goes into the object of explaining how to create a prototype instance object in the current JS execution Environment executable code (ECSTACK). Allocates memory to form a chain of scopes and a prototype chain. Changes the execution control and returns the object.

Summary: This new a object is prototype chain in ecstackand then this got return and leave Ecstack.

1. Context–ecstack

JS engine execution process is the life cycle of the JS object of the alternating process, JS engine parsing execution. When a child function is executed, the control of the engine operation is ceded to the child function. A child function is itself a function context.

Window. Ecstack = [];//Simulation execution environment, the actual execution environment contains the window global context

Note: The scope and parameter objects associated with the execution context are explained in the new section.

Execution Environment Ecstack memory timing structure diagram.

2. What–object

The ECMASCRIPT5 specification enriches the user-defined Object object and provides property attributes for the object.

See the Tutorial: http://www.w3school.com.cn/js/pro_js_referencetypes.asp

Note: JSON object extension, using JSON. Stringify (/*object*/) and Json.parse (/*string*/) Perform object serialization, sometimes depending on the Tojson () method of the referencing object.

3. Type–prototype Chain

JS is a meta-explanatory language, when the JS engine executes the JS code, the syntax structure is parsed, and the resulting object structure is placed in heap memory, called the prototype. All objects in memory contain an attribute [[prototype]] pointer to the prototype of the heap memory, and firefox,chrome such as the browser defines the property as __proto__ to display the call.

Sauce: Foo.__proto__àfoo.prototype

At the same time prototype object exists prototype, forming a prototype chain. When the JS engine instantiates the Window object to construct the global context this, the following prototype chain is generated in the heap memory:

Each rectangle in the diagram is a prototype object. Each prototype object has its own constructor function.

Sauce: Foo.prototype.constructor = = foo ();//Note here is the function, just JS allowed to write Foo.

I am comparing Java with JavaScript, although this may not be appropriate.

JavaScript concepts

Java Concepts

Predefined objects, such as Object

API objects, such as Java.lang.Object

Kernel

Jvm

The prototype object Object.prototype loaded into heap memory when the kernel initializes the window

After the JVM starts, the class information is object.class loaded into the method area.

Object ()//object.prototype. Constructor constructor function

Object constructor

var obj = new Object ();

Object obj = new Object ();

obj.__proto__ = = Object.prototype

Obj.getclass () = = Object.class;

The constructor constructor concept is a dynamic concept, meaning that the prototype object in the runtime kernel contains constructors. After understanding the predefined objects, prototype objects, prototype object constructors, and instantiating objects, you need to extend a concept: How to determine the object type.

Key words

Type

return value

Description

typeof

Unary operators

String

Base type undefined string number Boolean

The reference type Object function type functions.

The reason for not returning null: The object JS type value is present in the three-bit unit, 32 bits have 1-3 bits for the type TAG, and the other bits represent the real value. The tag bit of object is 000. The null mark bit is 00, and the final type is object.

instanceof

Binary operators

Boolean value

To determine whether a variable is an instance of an object except undefined null is to see if the object is on the prototype chain of the variable.

Constructor

Function

constructor function

var temp = obj.constructor.toString ();

Temp.replace (/^function (\w+) \ (\). +$/, ' $ ');

Prototype

Object

Prototype type

Object.prototype.toString.call (obj). Slice (8,-1). toLowerCase ();

At this point we can make the prototype chain memory structure diagram:

When querying the properties of an object, if the property does not exist for that object, the property is found in the prototype chain of the object if the object prototype is present. Returns the property if it exists, and returns undefined if the property is not found until the prototype is null.

JavaScript to find the property is to find the nearest, can not find his father.

4. Who–this

This is a property of the current execution environment context. JavaScript is single-threaded, meaning that the JS kernel executes the JS code switching context and this will change. If JS executes to code fragment A, stating that the previous level of content B containing fragment A is being loaded/instantiated, then B is this.

Ecstack = {VO: {...}, this:thisvalue};

Initial state

When the browser loads the request page, unloads the original event, parses and renders the HTML, drives the current event, and binds the current Window object. Each window has its own global object, and when the page is loaded, the window object instantiates and binds this.

function Main () {
window = new Window ();

This.call (window);//extend this environment object, in fact only the function object has the call method

|

No status

This piece does not have too much code to demonstrate. The individual has two points of understanding.

    1. A is called method A, the this in the A method is a.
    2. If there is no a method in a, the this in the A method is the prototype object B that contains the nearest method A in the a prototype chain.

function Foo () {}

Foo.prototype.foo = "Bar";

Foo.prototype.logFoo = function () {eval ("Console.log (This.foo)");//logs "Bar"}

var foo = new Foo ();

Foo.logfoo ();//foo call Logfoo method, only Foo prototype has Logfoo method, so Foo.prototype is this

Note: To determine whether a is a free attribute, use the hasownproperty method.

Note: You can use the with,apply,call,bind method to connect the this environment context to implement property inheritance, which is not explained too much here.

5. Do–newintroduce

The new keyword instantiates an object. The object instantiation process, the constant assignment of this, constructs the Parameter object arguments, and maintains the constructor property of the instance object.

Step

Throw a chestnut. To customize an object using a constructor:

1 function A (/* number*/ID,/*string*/name) {this.id = id; this.name = name;}

2 var a = new A (1);//a.__proto__ =a.prototype

The decomposition steps are as follows:

    1. Executes 1 lines, loads a object constructor and puts in memory, constructs the prototype chain

A.prototype.constructor=a () {...};

A () = new Function ();

Function () = NewObject ();

    1. When you execute 2 rows, instantiate a with a constructor and A.prototype scope to instance a

Var a = new A ();

A.call (A, _args);//_args.id=1;

    1. Constructs a Parameter object arguments object before executing an in-memory constructor A.prototype.constructor

arguments = A.prototype.slice.call (_args);; /Incoming Parameters

Arguments.callee ==this;//Parameter Object caller is the current function body

Note: Arguments.length represents the actual pass parameter, Arguments.callee.length represents the expected pass parameter

    1. When executing the in-memory constructor A.prototype.constructor, the attribute methods in the prototype chain are inherited according to the parameter assignment.

a.ID = arguments[1];//value is 1

A.name = arguments[2];//value is undefined

A.constructor = a.prototype.constructor= A () {...};//inherited

    1. return value

return A;

Ways

New Object method

Describe

Note

Construction method for using built-in objects in JS memory

var str = new String ("str");

Only built-in objects can be instantiated

Using JSON literals

var o = {' name ': ' Sapphire '};

Quick and easy way

Factory mode

Creates an object in a custom function and returns

Abstract Way

Constructor mode

function Foo (_args) {...};

var foo = new Foo (_args);

Common ways

Method cannot be shared

Prototype mode

function Foo (id) {Foo.prototype.id = id};

Cut off existing instances and prototype object relationships

Property sharing

Combination mode

function Foo () {...};

Foo.prototype = {fun:function () {}};

Constructor Pattern Construction Properties

Prototype Pattern Construction method

6. Result–return

The instantiated object is returned when the constructor does not have a special declaration return value.

Chapter three. Closure

The function closure is a kind of technique, especially is widely used in lambdas language. In Java, you can simulate closures in a way that uses anonymous functions.

1. Introduce

Closure = closure function + A set of free variables and name-bound store mappings, implementing the function of external access to function internal variables of the technology.

Principle: If a function contains intrinsic functions, then they can all see the variables declared therein, and these variables are called ' free ' variables. However, these variables can be captured by internal functions, and return from the higher-order function to achieve ' jailbreak ' for later use. The only thing to note is that the capture function must be defined within an external function. Variables that are used in a function without any local declarations (neither passed in nor locally declared) are the variables that are captured.

Note: More than 20% of the blogs in JavaScript are about closures, which are not covered here.

Cons: When applying, you need to analyze function variables, check if closures will interfere with each other, and check if instances of closures are the same.

Li Duan: When the closure function is instantiated, it is executed only once, and the variables that do not need to expose the outer environment are encapsulated inside and the external variables are reduced.

Chapter Four. Inherit

In ECMAScript, only implementation inheritance is supported, but signature inheritance (interface inheritance) implementation inheritance is basically inherited through the prototype chain.

How to Inherit

Example

Prototype chain inheritance

Sub.prototype = new Super ();

Constructor inheritance

function Sub () {super.call (this);}

Combining inheritance

Prototype inheritance

Object.create (prototype)

Chapter Five. Namespace

Above we contact the global variables and this concept, the front-end JS development, the non-canonical naming rules will lead to JS global variable confusion and even conflict.

The following code example regulates variable namespaces

Varglobal = {};

global.namespace= function (str) {

var arr = str.split ('. ');

var start = 0;

if (arr[0] = = ' GLOBAL ') {start = 1;}

for (var i = start; i < arr.length; i++) {

Global[arr[i]] = Global[arr[i] | | {};

GLOBAL = O[arr[i]];

}

};

Assume that a variable completes the A1 function in a function. b variable completes the A2 function in a function. C variable completes the B function. So

Global.namespace (' a.a1); a.a1.a = ...;

Global.namespace (' a.a2); a.a2.b = ...;

Global.namespace (' a.a1); B.C = ...;

While

Try to declare variables in the anonymous function rather than in the global environment.

Add more comments to your code.

Chapter Six. Reference

Firefox developer JS Document

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

IBM Developer Community

http://www.ibm.com/developerworks/cn/web/

About ECMA-262 Personal Sites

http://dmitrysoshnikov.com/

JavaScript oriented[Exploring Object-oriented JavaScript advanced language features]

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.