-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprivate-variable.html
More file actions
42 lines (39 loc) · 1.27 KB
/
private-variable.html
File metadata and controls
42 lines (39 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<script>
//严格来讲, JavaScript 中没有私有成员的概念;所有对象属性都是公有的。不过,倒是有一个私有
//变量的概念。任何在函数中定义的变量,都可以认为是私有变量,因为不能在函数的外部访问这些变量。
//私有变量包括函数的参数、局部变量和在函数内部定义的其他函数。
function MyObject() {
//私有变量和私有函数
var privateVariable = 10;
function privateFunction() {
return false;
}
//特权方法
this.publicMethod = function () {
privateVariable++;
return privateFunction();
};
}
//构造函数
function Person(name) {
this.getName = function () {
return name;
};
this.setName = function (value) {
name = value;
};
}
var person = new Person("Nicholas");
alert(person.getName()); //"Nicholas"
person.setName("Greg");
alert(person.getName()); //"Greg"
</script>
</body>
</html>