JavaScript functions and their prototype

Source: Internet
Author: User

first, the definitiona function can be defined by a declaration, or it can be an expression.
(1) Function declaration type:
Semicolons are used to separate executable JavaScript statements, because the function declaration is not an executable statement, so it does not end with a semicolon.
function A () {  console.log (' BBB ');}
(2) function expression:
The function expression ends with a semicolon because it is an execution statement.
var a = function () {  console.log (' AAA ');}
(3) declarative variants:
var a = function A () {  console.log (' BBB ');}
exactly equivalent to function B () {}
Second, function executionThe JavaScript parser places all the variables and functions declared within the current scope at the beginning of the scope, but only the declaration of the variable is advanced to the beginning of the scope, and the assignment is left in place.
Example 1:
var a = function () {  console.log (' AAA ');} function A () {  console.log (' BBB ');} A ();/Result: AAA
Example 2:
(function () {  console.log (nosuchvariable);}) ();//error, because the nosuchvariable variable is not defined at all
</pre><pre name= "Code" class= "JavaScript" > (function () {console.log (declaredlater);//"Undefined" var Declaredlater = "Now it ' s defined!"; Console.log (declaredlater);//"Now it ' s defined!"}) ();//The above code is correct and there is no problem.

Example 3:

var A;         Declares a variable with an identifier of afunction a () {}//declares a function, and a identifier of Aalert (typeof a);  Functionfunction A () {}var A;alert (typeof a);  Functionfunction A () {}var a = 1;alert (typeof a);  Numbervar a = 1;function A () {}alert (typeof a);  Number
Summary:
The declaration of a variable is advanced to the top of the scope, and the assignment remains in place;
The declarative function is "in advance";
function expression only the variable "is advanced", the function is not "advanced";
In the case of the same name, the variable is "advanced" and the function is "advanced" (that is, the function overrides the variable)
assignments are overwritten according to the order of the front and back!
third, function is Object [typeof instanceof]using the typeof operator in JavaScript to determine the function type will return "functions". But JavaScript functions are described as an object that is more accurate. JavaScript functions have properties and methods.
(1) typeof distinguish between objects and other primitive values
The data types of JavaScript are: primitive types (numbers, strings, booleans, nulls, undefined), and object types.
typeof[any type] return value (Boolean, string, number, object, undefined), and function
typeof 2;     ' Number ' typeof ' 2 ';   ' String ' typeof true;  ' Boolean ' typeof [];    ' object ' typeof null;  ' object ' typeof undefined; ' undefined ' var a = function () {}; typeof A; ' function '
for all built-in executable objects, typeof returns "function"
typeof new Number (2);     ' Object ' typeof new String (' 2 ');   ' Object ' typeof new Boolean (true); ' Object '
(2) instanceof[object instanceof class] Determines whether an object is an instance of a class
[] instanceof Object; true2 instanceof number; Falsenew Number (2) instanceof number; True
Example:
var a = function () {};var b = function () {};a.prototype = new B (); New A () instanceof B; Truenew A () instanceof Object; True
first determine the B.prototype if B.prototype returns true in the prototype chain of the A object, otherwise false is returned.
Note: All objects are instances of object.
(3) Extended Object.prototype.toString.call ([]) = = = ' [Object Array] ';
Iv. prototypeJavaScript objects have two different properties, one is the property of the object itself, and the other is inherited from the prototype chain.
in JavaScript, all instance objects of a class inherit properties from the same prototype object, so the prototype object is the core of the class.
(1) only the function has prototype, the object does not have
var b = {};b.prototype.bbb= ' BBB ';  Error B.prototype for Undefinedfunction B () {}   b.prototype.bbb= ' BBB '; Console.log (b);            Result: function B () {}console.log (b.prototype);  Result: b {bbb: "BBB"}console.log (B.BBB);        Results: Undefinedconsole.log (new B (). BBB);  Result: BBB
(2)prototype is the built-in property of the function (used to set the prototype of the function), and __proto__ is the built-in property of the object (used to set the object's prototype).
PS: Note Distinguishing functions and objects
function test () {}test.prototype;   Result: Test {}new test (). prototype;   Result: Undefined, object does not have prototypenew test (). __proto__;   Result: Test {}   function A () {     this.v= ' VVV ';} A.prototype; a {}new a.__proto__; A {}new a (). __proto__ = = = A.prototype;  True __proto__ of the instance object, pointing to the prototype of the function
(3) each Javasscript function automatically has a prototype attribute. The value of this property is an object that contains a unique non-enumerable property, constructor. The value of the constructor property is a function object.
function A () {     this.v= ' VVV ';} A.prototype.constructor = = = A; true[Physical address as]a.prototype.constructor; constructor attribute refers to this class a.prototype.constructor.__proto__ = = = A.__proto__ = = = Function.prototype; True object.prototype.constructor.__proto__ = = = Object.__proto__ = = = Function.prototype; True
PS: All constructors, __proto__ of functions point to Function.prototype, which is an empty function
(4) Example
Example 1:
function A () {}function B () {}a.prototype = {aaa: ' aaa '};b.prototype = A.prototype;var Aa1 = new A (); var bb1 = new B ();//aa1. prototype.aaa= ' xxx ';   Error, object no prototype A.PROTOTYPE.AAA = ' xxx '; Console.log (AA1.AAA);    Xxxconsole.log (BB1.AAA);    Xxx
add: a===b;//false A.prototype = = = B.prototype;//true

Example 2:
function A () {}function B () {this.bbb= ' bbb '}a.prototype = new B ();  Equivalent to A.prototype = {bbb: "BBB"};console.log (New A (). BBB); Result: BBB
Supplement: A.prototype = = = B.prototype; False
v. Example methods & static Methods(1) Example Method
function A () {}a.prototype.count = 0;var a1 = new A (); A1.count++;var A2 = new A (); a2.count++;a.prototype.count;  0
PS: Method similar to A.prototype.method = function () {}
(2) static method
function A () {}a.count = 0;new a (). Count ();  Undefined, can only be called with A.count
PS: Method similar to A.method = function () {}
(3) when the code var p = new person () is executed, new does the following several things:
A. Creating a blank object
B. Creating a pointer to Person.prototype
C. Pass this object through the This keyword to the constructor and execute the constructor
six, closed packagethe scope chain to function execution is still valid when the function is defined.
example-typical closures:
var scope = "global scope"; function Checkscope () {  var scope = "local scope";  function f () {    return scope;  }    return f ();} Checkscope (); Local scope
Example: A more common closure
function counter () {  var n=0;  return{    count:function () {      return ++n;    },    reset:function () {      n=0;    }}  ;} var C1 = new Counter (); C1.count (); 1var C2 = new Counter (); C2.count (); 1c1.reset (); C1 is not affected by 0,C2 c2.count (); 2
PS: Instance objects do not affect each other, methods within a single instance object, share private variables.
call the function indirectly by calling the method: Apply&call
function A () {  console.log (THIS.X+THIS.Y);} A.call ({x:100,y:100});  200function C () {  this.m = function () {    console.log (THIS.X+THIS.Y);}   } var c = new C (); C.m.call ({x:100,y:100});  200
call&apply The first argument is the parent object that is to invoke the function and becomes the value of this.
function. Call (object, parameter 1, parameter 2);
function. Apply (object, [Parameter 1, parameter 2]);//Array Form
Add:
function A (a,b,c,d) {
Turning a pseudo-array into a true array
var args = [].slice.call (arguments);
}
viii. functions in this
function A () {  console.log (this);  A {}   function B () {    console.log (this);  Window  }  B ();} New A ();
Special Note: function intrinsics this points to window
This problem has been modified in strict mode, and in non-strict mode, you can use a variable to receive an external function this for use by an intrinsic function, such as var.
Nine, callback (function as parameter)function A (callback) {
callback ();
}
A (function () {
console.log (' aaa ');
});
more flexible, the main page only need to provide the corresponding interface for sub-pages, the specific processing logic all child page processing.



JavaScript functions and their prototype

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.