Home  >  Article  >  Web Front-end  >  JavaScript scope and this keyword

JavaScript scope and this keyword

高洛峰
高洛峰Original
2016-11-28 14:14:441166browse

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