anonymous function self-executing principle and instanceof operator execution principle

Source: Internet
Author: User

Today received an RSS subscription in the "7 implementations of Javascript–arraylike", see the first realization is that the instant by!function () {} () this anonymous function self-execution way to light blind eyes. This writing is absolutely a force artifact, the code is as follows:

1!function () {2     //implemented by closures3     varList =function () {4         varList = [],5Self = {6 Constructor:list,7                 //If you want to be more like a native and define length as a property, then length needs to be maintained8Lengthfunction() {returnlist.length;},9Addfunction(item) {Ten List.push (item); One                 }, Aeqfunction(index) { -                     returnList[index]; -                 } the             }; -         returnSelf ; -     }; -     //Test +Console.group (' The first type-implemented by closures '); -     varDemo =NewList (); +Demo.add (' List-add () '); AConsole.log (' demo instanceof List:%c ' + (DemoinstanceofList), ' color:red; '); atConsole.log (' demo.constructor = = = List:%c ' + (demo.constructor = = = list), ' Color:blue '); -     //cannot access by index demo[0] this way -Console.log (' Member: [' + demo.eq (0) + ', ' + demo.eq (1) + '] '); -Console.log (' Length: ' +demo.length ()); -     //Watch the Demo object . - Console.log (demo); in console.groupend (); -}();

In fact-function () {} (); +function () {} (); ~function () {} () These can also implement the self-execution of anonymous functions, the principle is that when function () {} () preceded by an operator, the JS interpreter after the "see" operator, will continue to look for the value function () {} that is used for the calculation, and then execute the function to get the value for the operation. In the negation or addition of the operation, because JS will be in addition to null,undefined,0 and other individual numbers into the Boolan value of false, the other string, the object function will be converted to true, so the function of one-time negation operation will not throw an exception, do not change the function. Similarly, the addition is the same, JS will try to convert objects and functions to a number, get Nan without throwing an exception. This can be verified using the following code:

Console.log (!function () {        console.log (1);     });  will only print out false and will not print out 1console.dir (-function () {        console.log (1);    });  Only the Nan is printed

Obviously, using the function () {} () is more than using (function () {}) () one operation. When the JS interpreter knows that function () {} is an argument followed by a parenthesis, it calls the function, which is the same as assigning function () {} to a variable a, and then using the A () call. So why not call the function () {} () directly? In fact, we can see the error of calling in Chrome: uncaught syntaxerror:unexpected token ( which is the same as writing function (). It can be found that the JS interpreter parses function () {} () into function (); {} (); Why would you parse it like this? There is also why writing (function () {} ()) can also be performed correctly? We can go to the definition of the function, in the 6th edition of the JavaScript authoritative guide for the definition of a function: The function is defined using the Function keyword, which can be used in functions definition expressions or Function declaration statements. The syntax for a function definition expression is var functionname = function () {}; Function declaration statement syntax is function funcname () {}; So, if you do not write parentheses, The JavaScript interpreter attempts to parse the keyword function into a functional declaration statement (in the same way that the value of an operation can only be an expression and cannot be a declaration statement). Parentheses are used before the function, and the JavaScript interpreter correctly resolves it to a function-definition expression (anonymous). This allows you to specify that theunexpected token ( error is due to the expect function name.

instanceof

Let's take a look at the top 22 lines of code,

Demo instanceof List   =====> false

In fact, because the list has a return value, all var demo = new List (), in fact, equivalent to var demo = List (); All demos are not instances of the list. Look at the definition of instanceof:

The instanceof operator expects the left operand to be an object that has operands that identify the class of the object. If the object on the left is an instance of the right-hand class, the expression returns true, otherwise false is returned. The classes of objects in JavaScript are defined by the constructors that initialize them. In this case, the right operand of instanceof should be a function that throws a type error exception if the right operand is not a function. Note that all objects are instances of object.
In order to calculate the expression o instanceof f,javascript first computes the f.prototype and then finds O in the prototype chain, if found, then O is an instance of f (or the parent of f), then the expression instanceof returns ture. The principle is that there is a hidden member __proto__ in Object o, which points to the prototype of its parent class, and if the prototype of the parent class is an instance of another class, there is also a prototype in the prototype object that __proto__ points to another class, which is the prototype chain.
Console.log (p.__proto__ = = = Person.prototype); Trueconsole.log (li.__proto__ = = = List.prototype); Falsefunction inherit (p) {    function f () {}    f.prototype = p;    return new F (); var student = inherit (p); The student object inherits the P object. Console.log (student.__proto__ = = = Person.prototype); Falseconsole.log (student.__proto__.__proto__ = = = Person.prototype); True

  

anonymous function self-executing principle and instanceof operator execution principle

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.