Home > Web Front-end > JS Tutorial > body text

javascript定义变量时加var与不加var的区别_基础知识

WBOY
Release: 2016-05-16 16:25:21
Original
1420 people have browsed it

一、外部的为全局,内部的为局部变量。

二、加var为局部变量(在方法内),不加var为全局变量(当方法内有一次使用后)

复制代码 代码如下:


在上面的test方法内,当把local变量的var去掉后,local就变成了全局变量,但是在局部不使用local,则这个local作为全局是无效的。

为了验证这点,我把test方法内部唯一使用local变量的这句代码注释掉.发现在外部也打印不出来了。

总结:全局变量可以不声明var 函数内变量必须声明var,在定义全局变量时加或不加var关键字没什么影响;但在定义局部变量时如果不加var关键字javascript解释程序会将其解释为全局变量。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!