3. Scope All object-oriented languages have some form of scope, and JavaScript is no exception. In JavaScript, scope is divided by functions, not by blocks (while, if, etc.).
Let’s first look at a simple scope example.
]
In the if block, although The value of foo is changed to "b", but it is still in the global scope, so the output result is "b".
An interesting feature of the browser-based JavaScript language is that all variables belonging to the global scope are properties of the window object.
Look at the code below:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
The result may be a bit surprising to you , but the result is definitely correct. The result of code ② is to output "b" instead of "c". The reason is related to scope. Although change() is called to change the value of foo, the change at this time only
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
In JavaScript, if the variable If not explicitly defined, it is defined globally. So after calling change(), the value of global foo will be modified. The final output is "c".
4. Context object
[Ctrl A Select all Note:
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
本例中,我们把obj.hide变量的上下文对象变为window对象时,代码写得并不好理解。幸运的是,JavaScript提供了一套更好的方法来解决。
现在我们有请call和apply两位先生上场,通过它们也可以完成同样的功能。先看call:
通过obj.hide.call(window),我们将此时的上下文对象改为window对象。call方法的第一个参数就是上下文对象。
call方法也可以传递更多的参数,如下所示:
另外apply方法跟call类型,它的第一个参数也是上下文对象,不过后面的参数则是一个数组。如下所示:
最后我们来看一个通过上下文,call和apply结合的例子。
在setBodyColor函数中,apply的第二个参数是数组,而前面我们讲过,arguments 也是一个伪数组,那么它们2个能联系起来吗?
把 changeColor.apply( document.body , ["blue"]); 改为 changeColor.apply( document.body , arguments );,
然后给setBodyColor();函数传参数。如下代码所示:
通过这些例子,你也许对上下文的概念比较熟悉了。上下文在面向对象的编程中非常重要。