In-depth understanding of some javascript features (static scope, this pointer, closure)

Source: Internet
Author: User
These are some of the summaries of reading books over the past two days. It is not a detailed explanation. It mainly records key points. About the static scope of javascript: the scope of 1javascript is completely determined by the function, and brackets are not independent scopes. 2javascript is almost a summary of the two days of reading. Here, it is a summary. It is not a detailed explanation. It mainly records key points. About the static scope of javascript: 1. The scope of javascript is completely determined by the function, and brackets are not independent scopes. 2. The special feature of javascript is that the function can read external variables. The function cannot read internal variables. The sub-object searches for all parent object variables at the first level. All the variables of the parent object are visible to the child object, and vice versa. 3. The meaning of the static scope is that the nesting relationship of the function scope is determined by the definition, not the call. It becomes the lexical scope, and its scope nesting relationship is determined during syntax analysis, rather than runtime. For example: [javascript var scope = 'out' var f1 = function () {console. log (scope) ;}; f1 (); // out var f2 = funtion () {var scope = 'in'; f1 () ;}f2 (); // out indicates that the function f1 has completed lexical analysis when searching for variable definitions, instead of waiting until f1 is called. 4. variables that do not directly assign values through var Declaration are global variables. Context object (this pointer): 1. Context object refers to the environment where the called function is located. Its function is to reference the object itself that calls a function. Compared with the static scope, this points to the object that calls the function at the time of function call. This pointer is a supplement to the static scope. [Javascript] var obj = {name: 'js', show: function () {console. log (this. name) ;}}; obj. show (); // output JS var foo = {name: 'foo', show: obj. show}; foo. show (); // output foo. When the show function is called by the foo object, this pointer points to the foo object. Put this. directly change name to this. The output result is [javascript] {name: 'js', show: [Function]} {name: 'foo', show: [Function. To better understand this problem, run the following code: [javascript] name = 'foo' function f () {console. log (this) ;}; f (); the following result is displayed: [javascript] {ArrayBuffer: [Function: ArrayBuffer], Int8Array: {[Function: Int8Array] BYTES_PER_ELEMENT: 1}, Uint8Array: {[Function: Uint8Array] BYTES_PER_ELEMENT: 1}, Uint8ClampedArray: {[Function: Functions] BYTES_PER_ELEMENT: 1}, Int16Array: {[Function: Int16Array] BYTES_PER_ELEMENT: 2}, Uint16Array: {[Function: Uint16Array] BYTES_PER_ELEMENT: 2}, Int32Array: {[Function: Int32Array] BYTES_PER_ELEMENT: 4}, Uint32Array: {[Function: Uint32Array] functions: 4}, Float32Array: {[Function: Float32Array] BYTES_PER_ELEMENT: 4}, Float64Array: {[Function: Float64Array] BYTES_PER_ELEMENT: 8}, DataView: [Function: DataView], feature: [Function], DT RACE_NET_STREAM_END: [Function], functions: [Function], functions: [Function], DTRACE_HTTP_SERVER_REQUEST: [Function], DTRACE_HTTP_SERVER_RESPONSE: [Function], DTRACE_HTTP_CLIENT_REQUEST: [Function], functions: [Function], global: [Circular], process: {title: 'node', version: 'v0. 10.10 ', moduleLoadList: ['binding evals', 'binding natives ', 'nativemodu Le events ', 'nativemodule buffer', 'binding buffer', 'nativemodule assert', 'nativemodule util', 'nativemodule path', 'nativemodule module', 'nativemodule fs ', 'binding fs', 'binding constants', 'nativemodule Stream', 'nativemodule _ stream_readable ', 'nativemodule _ stream_writable', 'nativemodule _ stream_duplex ', 'nativemodule _ stream_transform ', 'nativemodule _ stream_passthrough ', 'nativemodule c Onsole ', 'binding tty_wrap', 'nativemodule tty ', 'nativemodule net', 'nativemodule timers', 'binding timer_wrap ', 'nativemodule _ linklist', 'binding cares_wrap ', 'binding signal_wrap '], versions: {http_parser: '1. 0', node: '0. 10.10 ', v8: '3. 14.5.9 ', ares: '1. 9.0-DEV ', uv: '0. 10.10 ', zlib: '1. 2.3 ', modules: '11', openssl: '1. 0.1e '}, arch: 'x64', platform: 'darwin', argv: ['node', '/Users/hanbo/ Tmp/test. js'], execArgv: [], env: {TERM_PROGRAM: 'apple _ Terminal', TERM: 'xterm-256color', SHELL: '/bin/bash', TMPDIR: '/var/folders/nc/_ Folder/T/', Apple_PubSub_Socket_Render: '/tmp/launch-FS3ke9/Render', TERM_PROGRAM_VERSION: '200', OLDPWD: '/Users/hanbo', TERM_SESSION_ID: 'e96d82c5-D31B-4B22-B2FC-AC53AF5D862F', USER: 'hanbo', COMMAND_MODE: 'unix2003 ', SSH_AUTH_SOCK:'/t Mp/launch-DHqCvG/Listeners ', _ CF_USER_TEXT_ENCODING: '0x1f7: 25: 52', Apple_Ubiquity_Message:'/tmp/launch-h9jxfu/Apple_Ubiquity_Message ', PATH: '/opt/local/bin:/opt/local/sbin:/usr/bin:/usr/sbin:/usr/local/bin: /opt/X11/bin:/usr/local/git/bin:/usr/local/homebrew/bin ', PWD:'/Users/hanbo/tmp ', LANG: 'zh _ CN.UTF-8 ', SHLVL: '1', HOME:'/Users/hanbo', LOGNAME: 'hanbo', DISPLAY: '/tmp/launch-V T5lf3/org. macosforge. xquartz: 0', _: '/usr/local/bin/node'}, pid: 2028, features: {debug: false, uv: true, ipv6: true, tls_pnp: true, tls_sni: true, tls: true}, _ needImmediateCallback: false, execPath: '/usr/local/bin/node', debugPort: 5858, _ getActiveRequests: [Function], _ getActiveHandles: [Function], _ needTickCallback: [Function], reallyExit: [Function], abort: [Function], chdir: [Function], Cwd: [Function], umask: [Function], getuid: [Function], setuid: [Function], setgid: [Function], getgid: [Function], getgroups: [Function], setgroups: [Function], initgroups: [Function], _ kill: [Function], _ debugProcess: [Function], _ debugPause: [Function], _ debugEnd: [Function], hrtime: [Function], dlopen: [Function], uptime: [Function], memoryUsage: [Function], binding: [Function], _ usingDomains: [Function], _ tickInfoBox: {'0': 0, '1': 0, '2': 0}, _ events: {SIGWINCH: [Function]}, domain: null, _ maxListeners: 10, EventEmitter: {[Function: EventEmitter] listenerCount: [Function]}, _ fatalException: [Function], _ exiting: false, assert: [Function], config: {target_defaults: [Object], variables: [Object]}, nextTick: [Function: nextTick], _ nextDomainTick: [Function: _ nextDomainTick], _ ti CkCallback: [Function: _ tickCallback], _ tickDomainCallback: [Function: _ tickDomainCallback], _ future: [Function: _ tickFromSpinner], maxTickDepth: 1000, stdout: [Getter], stderr: [Getter], stdin: [Getter], openStdin: [Function], exit: [Function], kill: [Function], addListener: [Function], on: [Function], removeListener: [Function], mainModule: {id :'. ', exports :{}, parent: null, filename: '/Users/hanbo/tmp/test. js', loaded: false, children: [], paths: [Object] }}, GLOBAL: [Circular], root: [Circular], Buffer: {[Function: buffer] isEncoding: [Function], poolSize: 8192, isBuffer: [Function: isBuffer], byteLength: [Function], concat: [Function]}, setTimeout: [Function], setInterval: [Function], clearTimeout: [Function], clearInterval: [Function], setImmediate: [Function], clearIm Mediate: [Function], console: [Getter], name: 'foo'} is the root object of the Function called by node. When a function such as f1 () is called directly, this object is called. Next, we will change the global variable name = 'foo' defined in the first line of the above Code to the local variable definition: var name = 'foo' and find that the name attribute is not in the root object. The global variables in javscript are globally visible throughout the project. Run the following code: In the test1.js file: [javascript] exports. test1 = function () {console. log (name) ;}; in test. in the js file: [javascript] var test1 = require ('. /test1 '); [javascript] view plaincopyname = 'foo' test1.test1 (); run: node test. the js result is: foo. There are some questions about global variables that need to be discussed in depth. We will continue to discuss them in the next article in view of the deviation from the topic here. Back to the previous question: 2. When we mention the context object this, we have to say the call and apply methods. They use different objects as context to call a function. When this is used in a function, the object that calls the function is used as the context. When the call or apply method is used, you can specify the context for the function: [javascript] var user = {name: 'foo', show: function (obj) {console. log (this. name + 'doesnt give a' + obj) ;}; var bar ={ name: 'bar'}; user. show. call (bar, 'shit'); // output: bar doesnt give a shit. For the call method, the first parameter in the brackets is the bound context object, the following parameters are the parameters for calling a function. The call method must be explicitly called every time you bind a specified context. If you use the bind function, you can bind it permanently: [javascript] var user = {name: 'foo', show: function (obj) {console. log (this. name + 'doesnt give a' + obj) ;}}; var bar ={ name: 'bar'}; bar. func = user. show; bar. func ('duck '); bar. func1 = user. show. bind (user, 'duck '); bar. func1 (); output: bar doesnt give a duckfoo doesnt give a duck. After bind is used to bind the context, the context is determined no matter who calls it. At the same time, we can see that the bind method also has the function of permanently binding the parameter list. About closures: 1. we know from the static scopes we mentioned earlier that the external function cannot access the local variables defined inside the function, and a function can access the variables defined outside the function. Therefore, when we want to access the internal variables of a function, we can define another function within the function and then return this internal function. [Javascript] var func = function () {var num = 123; var count = 1; var get = function () {count ++; num --; console. log (num); return count ;}; return get ;}; var counter = func (); console. log (counter (); console. log (counter (); run the preceding code to obtain the result: 12221213 when a function is called and an internally defined function is returned, a closure is generated. The closure includes the returned function and the definition environment of the function. 2. The function of the closure: the closure mainly has two main functions: the first is to implement callback function nesting, and the second is to hide the details of the object. The article on the first role will be further analyzed later. Because we also need to explore the implementation mechanism of callback functions. You can understand how to hide object details: Because internal variables of a function are invisible to the outside, we can create a function object in the form of a closure, and internal data of a function cannot be directly accessed from outside, internal data can only be returned through the internal defined accessors function.
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.