标签:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js01_hello</title>
<meta name="author" content="Administrator" />
<script type="text/javascript">
for(var i=0;i<10;i++) {
}
//在js中没有块作用域,不管是使用循环还是判断之后,这个变量会一直存在
/*
* 所以当在全局使用某个变量进行循环或者判断之后,这个变量可能会影响
* 到函数中的变量,所以在特殊情况不要使用全局变量,而且使用全局变量
* 在作用域链的最上层,访问是最慢的
*/
var i;//此时会认为是无效语句,除非使用var i = 0;
alert(i);
</script>
</head>
<body>
</body>
</html>
=====================================================
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js01_hello</title>
<meta name="author" content="Administrator" />
<script type="text/javascript">
/*
* 在一个团队进行开发时,可能会涉及到定义同名的全局变量,所以在开发中
* 一定养成如下习惯,将全局变量的代码放到一个匿名函数,并且马上调用
* 匿名函数,这样也可以执行全局变量的代码,但是这些变量就被控制在开发
* 人员想要控制的作用域中了
*/
//在function的{}后不能直接调用,一定要加上括号
// function(){
// for(var i=0;i<10;i++) {
//
// }
// }();
(function(){
for(var i=0;i<10;i++) {
}
})();
function fn() {
alert(i);
}
fn();
</script>
</head>
<body>
</body>
</html>
=====================================================
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js01_hello</title>
<meta name="author" content="Administrator" />
<script type="text/javascript">
function Person(name) {
/**
* 此时就没有办法直接访问name这个属性,因为没有this.name
* 要访问name只能通过this.getName,this.setName
* 但是使用这种方式创建私有变量带来的问题是,每个对象都存储大量的函数
* 解决的办法是通过静态私有变量来解决
*/
this.setName = function(value) {
name = value;
}
this.getName = function() {
return name;
}
}
var p = new Person("aa");
alert(p.getName());
p.setName("bb");
alert(p.getName());
</script>
</head>
<body>
</body>
</html>
=====================================================
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js01_hello</title>
<meta name="author" content="Administrator" />
<script type="text/javascript">
var Person;
(function(){
//name正在函数结束之后就消失,在外面是无法引用的
var name = "";
Person = function(value){
name = value;
}
Person.prototype.setName = function(value) {
name = value;
}
Person.prototype.getName = function() {
return name;
}
})();
var p1 = new Person("aa");
alert(p1.getName());
p1.setName("bb");
alert(p1.getName());
</script>
</head>
<body>
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/aicpcode/p/4288657.html