search
HomeWeb Front-endJS TutorialJavaScript scope and this keyword

As a programmer, you may have long been accustomed to references (or pointers) that refer to the current object in object-oriented languages, such as this in c++ or self in python, which of course have OO attributes (javascript is actually more of a JavaScript, a so-called functional language, also has a pointer (or reference) that refers to the object of the current property, which is the this keyword.

In order to understand this keyword, if you just want to remember one sentence, it should be that this keyword always points to the owner object (execution space) of the current function. As for how to understand this sentence, please refer to the detailed description below .

So what is scope?

The explanation in wikipedia is In computer programming, scope is an enclosing context where values ​​and expressions are associated. Chinese is the so-called scope, which specifies the context (execution space that can be referenced) associated with a value or expression.

What does scope have to do with this? From the above definition, this always points to the object currently referencing this function, and when you want to determine the object currently referenced, you have to figure out the scope of the current function. See the analysis below for details.

this keyword

Please see a few examples below.

A python example:

class Person(object):
"""a person class
    """
def __init__(self, name):
self.name = name    #这里的self指向的是实例化后的对象,如下面中的Magic
def get_name(self):
return self.name
Magic = Person("Magic")
print Magic.name

A javascript example:

window.name = "Magic from window"
var get_name = function(){
    // this的具体指向只能在运行时才能确定,也就是确定运行时调用其的对象
    return this.name;   
};
// 输出Magic from window, get_name调用的对象为window
alert(get_name());  
var obj = {}
obj.name = "Magic from obj";
// 输出Magic from obj, 我们强制地使用了 apply来更改调用的对象,使其指向obj
alert(get_name.apply(obj)); 
var innerobj = {
    "name" : "Magic from innerobj"
};
innerobj.get_name = get_name;   // 使得innerobj的get_name方法指向了global scope的get_name函数
alert(innerobj.get_name()); // 输出Magic from innerobj, 此时this指向的是innerobj

So judging from the above simple example, this can only determine its specific pointer at runtime, and only then can it know its calling object. And this is also an important feature of dynamic languages.

So how to determine the reference object currently pointed to by this? It can usually be judged like this:

If it is called in the global scope (see the description below to clarify what the global scope is), it points to the top-level object window of bowser. For example: get_name()

If, something like this Reference to innerobj. get_name(), it is obvious that this points to innerobj

If we use apply or call to point to the forced reference object, it will also obviously point to the forced object, such as get_name. apply(obj).

About apply and call

These two keywords can be easily understood as coercion of this reference object (running space). The syntax of the two is as follows:

fun.call(object, arg1, arg2, .. .)

fun.apply(object, [arg1, arg2, ...])

The purpose of both is the same (dynamically changing the running space of the function, or changing the object pointed to by this), just providing The calling method on the parameters of the function is different.

The sample code is as follows:

var test_call_apply = function(name, gender, school){
alert(this.age + name + gender + school);
};
test_call_apply.call({age:24}, "Magic", "male", "ISCAS");
test_call_apply.apply({age:24}, ["Magic", "male", "ISCAS"]);

scope details

var global_scope = "I'm global";
var fun = function(){
var fun_scope = "I'm in fun scope";
return innerfun(){
var inner_func_scope = "I'm in the inner fun scope";
return global_scope + fun_scope + inner_func_scope; //此处的引用是重要的,请特别注意
};
};
alert(fun()());

Please note the above code, where:

global_scope It is the global scope

fun_scope It is the scope of a function

inner_func_scope is the scope of a function located within a function

You can also continue to embed functions, then several scopes will be generated.

So a question arises, why can the innerfun method reference variables that are not in its own scope?

Before answering this question, we need to introduce a concept scope chain. The so-called scope chain refers to a chain of priority and related scopes formed in the JavaScript code.

Take the above code as an example,

For the global scope, it will create a global scope chain for itself (of course, at this time, this chain only has one scope).

For the scope of the fun function, it first establishes a scope chain that is the same as global, and then adds its own scope (at this time, this chain has 2 scopes), similar to this structure: global==> fun

For innerfun, in addition to the chain owned by the fun function, it will also add its own scope (of course, this chain has 3 scopes at this time), similar to this structure: global==>fun= =>innerfun

scope chain has the following characteristics:

Ordered

Whenever a function is created, a scope will be automatically generated and added to its own scope chain

This chain is similar to a stack. When searching When looking up variables, always start from the top first


In fact, it is easy to understand. When calculating an expression, it will search its own scope chain from top to bottom. If it finds it, it will return immediately. If this value is not found after searching the entire chain, undefined will be returned.

This search mechanism also determines that the scope usually located at the front end of the chain has a higher priority.

For example, when javascript calculates the expression global_scope + fun_scope + inner_func_scope;, it will look for the scope chain in the above image to determine the final result.

一些说明

如果你弄清楚了上面的论述,应该说你对this关键字和scope已经具有完全的知识基础了,但是我们需要在实际中更好地使用和理解这些概念,这样才能把能力上升到别一个层次,这也即所谓的理论与实践的关系。

请看下面这个例子:

var change_color = function(){
this.style.color = "red";
};
window.onload = function(){
var text = document.getElementById("text");
text.onclick = change_color;    //此时this指向的是text这个对象(dom对象)
};
// 下面这行代码是在body中
//这点需要特别注意, inline script指向的是window,此处会无定义  
<span id="another" onclick="change_color()">My color will be changed2.</span>

需要特别注意的是:

inline event registration中的this并非指向的是自己的dom节点,而是global scope的window,这点可以从上面的例子中得到证明

这种inline event registration是不可取的,推荐的是 Unobtrusive JavaScript (处理逻辑和页面结构相分离)

javascript 是一种非常强大的动态语言,它是披着C语言外衣的函数式语言,如果你只当作它是一种类C的命令式语言,那么你的知识层次还过于低,而倘若你能够理解到javascript 的函数式语言本质,你在运用 javascript,理解 jQuery 及其它的库,甚至自己写一些 javascript 都会游刃有余的。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)