javascript-functions and oop-Learning notes

Source: Internet
Author: User

JavaScript authoritative Guide To learn notes, Forbidden reprint!

6. Functions

Function Call Method:

Direct call: foo ();

Method invocation as an object: Obj.method ();

New:new Foo ();

Call/apply/bind:func.call (obj);

If there is no return statement in the function object or return is the base type, if there is this return value of this,

(1) Creating a function

~ function declaration: Functions foo (A, b) {...}

~ Function Expression:

1) var add= function (A, b) {...};

2) immediately executes the function expression (functions () {...}) ();,!function () {...} ();

3) return function as returned value () {...};

4) named function expression var add= function foo () {...};

For example, Var func=function nfe () {};

alert (FUNC===NFE); Ie6-8 return FALSE,IE9 error NFE is not defined

var func=function nfe () {/*......*/nfe ();}; Recursive invocation. If there is no NFE, it can be called recursively using Func, so it is not commonly used.

~function Constructor: Var func=function (' A ', ' B ', ' Console.log (a+b); '); /Not common

The difference: The function declaration is pre-set and is called by the function name in the scope that defines the function;

function expressions and function constructors allow anonymous, immediate invocation;

The function constructor does not have a function name.

(2) This

This for global scope: point to Window

This is the general function: Point to Window in the browser, point to Global object in node. js

This is the function that acts as an object method: points to the object

The This on the object prototype chain: The object of the method on the prototype chain of a function that points to the object

Object Get/set The function of the method this: points to the object

~ ~New andthis:

function MyClass () {this.a=37;}//this points to an empty object, and the prototype of the object is Myclass.prototype;

var o=new MyClass (); This is assigned to O as the return value of the MyClass function;

O MyClass {a:37}

O.A; 37

~ ~call/apply method and this:

The name of the function. Call (object, ARG1,ARG2,ARGN)

The name of the function. Apply (object, [Arg1,arg2,argn])

The This object is pointed to in the function and the value to the function is assigned to it. The difference is that the form of the transfer parameter is different.

For example, function Add (b,c) {return this.a+b+c;} var o={a:1}; Add.call (o,2,3);

6

function Add (b,c) {return this.a+b+c;} var o={a:1}; Add.apply (o,[4,5]);

10

For example, function foo (x, y) {console.log (x,y,this);}

Foo. Pager (100,1,2);

1 2 Number {[[Primitivevalue]]: 100} (if the first parameter is not an object, it is converted to the object type)

Foo. Pager (null);

Undefined undefined Window

~ ~Bind method withThis (ES5 provided method, ie9+ only support)

The name of the function. Bind (object) causes this object to be pointed to in the function.

bind vs. New and this

such as function foo () {This.a=100;return this.b;}

var func=foo.bind ({b:1});

Func function foo () {This.a=100;return this.b;}

Func (); 1

New Func (); Foo {a:100} (when new calls the function, this still points to an empty object, the prototype of which is func.prototype and will not be changed by bind)

(3) Arguments argument

Foo.name: Function name, foo.length: Number of function parameters, Arguments.length: Number of arguments,

Arguments.callee is a pointer to the function that owns the arguments.

When there are many parameters, bind and currying can be used:

For example, function Add (a,b,c) {return a+b+c;}

var fun=add. bind (UNDEFINED,100);

Fun (All); 103 (This point does not matter, Undefined/null can)

var fun2=fun. bind (undefined,200);

FUN2 (1); 301

? (not seen) Bind method simulation

(4) Closures

Problem: garbage collection mechanism? Performance optimizations: Circular references?

For example, function outer () {var a=10; return function () {return A;} }

var func=outer ();// function () {return A;} A global variable is assigned as the return value, so a is always in memory, and local variable a inside it can be accessed outside of the outer function.

Func (); 10

In JavaScript, a global variable can be read inside a function, and a local variable inside a function cannot be read outside the function.

How do I read a local variable inside a function from outside the function? Define a function inside the function.

Advantages: Encapsulation

Cons: Local variables within the parent function cannot be freed, wasted space, memory consumption

A function as an object is passed as a return value, and a language like this has the concept of closure.

(5) Scope

Global scope

function scope

Eval scopes, such as eval ("Var a=1;") )

ES6 starts with block-level scopes

Purpose: Use function scope encapsulation.

? (not seen) ES3 execution context

7. OOP (Object-oriented programming)

Question: What are the attribute methods for Object.prototype on the prototype chain?

Answer: ValueOf, toString, hasOwnProperty,

An object is an instance of a class, and an object is the basic unit of a program.

Features: inheritance, encapsulation, polymorphism, abstraction

(1) prototype

For example, function Student () {...}

var bosn=new Student ();

Student.prototype is a preset object property on the function object Student, which acts as a Student.prototype prototype when you use new to construct Student instance bosn.

Student.prototype. constructor points to student itself (constructor: Meaning of the constructor)

Adding or removing a property on Student.prototype affects the instance bosn it creates;

If you modify student.prototype directly, it does not affect the instance bosn that you have created before you modify it.

However, the newly created instance will be affected later.

(2) instanceof

Object instanceof Function Constructor:

Determines whether the function constructor. prototype appears on the object's prototype chain. If the right side is not a function object, the error will be returned if the left side is not the object but the base type.

For example, New Object () instanceof Array;

False because the new object ()-->object.prototype-->null, so there is no array.prototype on the prototype chain of the left object

(3) Ways to implement inheritance

function Student () {...}

function person () {...}

Student.prototype=new person (); Not recommended

student.prototype=object.create (person.prototype); Recommended (but not supported after ES5)

(4) Analog reload

example, function person () {

var args=arguments;//assigning an argument to a variable

if (typeof args[0]=== ' object ' && Args[0]) {

&& Args[0] is the parameter to filter null (because typeof Args[0] is also an object)

if (Args[0]) {

This.name= Args[0].name; }

if (Args[1]) {

This.age= Args[1].name; }

}

else{

if (Args[0]) {

This.name= Args[0]; }

if (Args[1]) {

This.age= Args[1]; }

}

}

var bosn=new person (' bosn ', 27);

var bosn2=new person ({name: ' Bosn2 ', age:27});

(5) Chained calls

For example, function AddClass () {}

Addclass.prototype.add=function (str) {

Console.log (str+ ' is added ');

return this;

The}//of the function that is the object method points to the object Addclass.prototype

var myman=new addclass (); Myman's prototype points to Addclass.prototype

Myman.add (' A '). Add (' B '). Add (' C ');

Ais added

Bis added

Cis added

? (not seen) 9-1 abstract class

(6) Example: detector

Subclass, base class, Detect (), analyze () current environment, implement two detectors container and link

! function (Global) {

Detectorbase base class

function Detectorbase (configs) {

if (!this intanceof detectorbase) {

throw new Error (' Do not invoke without new '); }//must use new call Detectorbase,this to point to the object, the prototype of the object points to Detectorbase.prptotype, so this intanceof detectorbase is true

This.configs= configs;

This.analyze ();

}

Detectorbase.prototype.detect=function () {throw new Error (' Not implemented ')};

Detectorbase.prototype.analyze=function () {...};

Concrete Class Linkdetector

function Linkdetector (links) {

if (!this intanceof linkdetector) {

throw new Error (' Do not invoke without new '); }//must be called with new

This.links=links;

Detectorbase.apply (this,arguments); Call base class

}

Concrete Class Containerdetector

function Containerdetector (containers) {

if (!this intanceof containerdetector) {

throw new Error (' Do not invoke without new '); }//must be called with new

This.containers=containers;

Detectorbase.apply (this,arguments); Call base class

}

Inherit first

function inherit (subclass, superclass) {

Subclass.prototype =object.create (superclass. prototype);

Subclass.prototype.constructor= Subclass;

}

Inherit (Linkdetector, detectorbase);

Inherit (Containerdetector, detectorbase);

Scale again to prevent overwriting

Linkdetector. Prototype. Detect=function () {...};

Containerdetector. Prototype. Detect=function () {...};

Freeze (make extensible, Configurable, WRITABLE:FALSE,ES5 methods)

Object.freeze (detectorbase);

Object.freeze (detectorbase. prototype);

Object.freeze (Linkdetector);

Object.freeze (linkdetector. prototype);

Object.freeze (Containerdetector);

Object.freeze (containerdetector. prototype);

Exposed to global objects (three properties such as Linkdetector are added on global objects, and enumerable, configurable, Writable:false)

Object.defineproperties (global,{

Linkdetector:{value:linkdetector},

Containerdetector:{value:containerdetector},

Detectorbase:{value:detectorbase}

});

} (this); Execute function Now this concludes, it's so long.

Prototype chain:linkdetector--> Linkdetector. Prototype (Detect method)--detectorbase. Prototype (detect, analyze method)

Call

var cd=new containerdetector (' ABCDEFG ');

var ld=new linkdetector (' http://www.imooc.com/');

CD. Detect ();

ld. Detect ();

The probe is finally over.

javascript-functions and oop-Learning notes

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.