JS的面向对象.
所谓JS面向对象当然不会像JAVA,AS3那样的完全面向对象语言所具有继承、多态,以及接口这样的概念。这里的面向对象只是创建JS“对象”后,调用“对象”中的方法。比如:
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
43
44
| <html>
<head>
<title>javascript_oop</title>
<script type="text/javascript">
var Test = function() {
// 私有属性
var key;
// 私有方法
function private1() {
alert ("测试私有方法private1");
}
//测试私有
private1();
return {
// 公用属性
p : 1,
// 公用方法
getkey : function() {
return this.key;
},
setkey : function(key) {
this.key = key;
}
};
};
// 测试公用
var t = new Test();
t.setkey(100);
alert('调用公用属性:' + t.p);
alert('调用公用方法:' + t.getkey());
function t1() {
t.private1();
}
</script>
</head>
<body>
<a href="javascript:t1()">测试调用私有方法</a>
</body>
</html> |
首先创建的var Test = function() 可以看做一个类似java的类,类名就是Test。之后创建对象var t = new Test();的时候就执行了Test = 后面的匿名函数function() {}(就像JAVA的构造函数一样),里面return以外的部分类似JAVA中private私有的方法和属性,至于return里面就是公用的public方法和属性。其实到这就很明白了,就是return回来一个数组当做公用,从而来达到类似“对象”的效果。
其中上面的js在运行过程中,第一次alert就是在创建对象的时候执行了类似JAVA的构造函数的匿名函数function() {},测试了私有方法的调用。之后的两次alert测试了公用属性和公用方法,如果你点击“测试调用私有方法”来调用对象“私有”的方法就会报错,因为这是不被允许的。
公司新的SPRING架构系统,全部是用EXT+DWR展示,至于EXT的JS几乎都是这种写法。只是照猫画虎的用觉得很简单,不过确实应该认真去看过为什么这样写。
之后另一个实现JS对象,这是我在网络搜索的一个例子:
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
43
44
45
46
47
48
| <html>
<head>
<title>javascript_oop2</title>
</head>
<body>
<script type="text/javascript">
//构造函数
function Animal(name, sound, age) {
this.name = name;
this.sound = sound;
this.age = age;
}
//类属性
Animal.description = 'animal';
//类静态方法
Animal.descript = function() {
document.write('This is a \'' + this.description + '\' class!<br>');
}
//实例后对象方法
Animal.prototype = {
sayName:function(str) {
document.write('My name is:' + this.name + str + '<br>');
},
shout:function() {
document.write('My sound is:' + this.sound + '!!!<br>');
},
sayInfo:function() {
document.write('Name = ' + this.name + '; Age = ' + this.age + '<br>');
}
};
//测试类
Animal.descript();
var dog = new Animal('dog', 'wang wang', 5);
var cat = new Animal('cat', 'miao miao', 3);
dog.sayName('.--wang');
cat.sayName('.--miao');
dog.shout();
cat.shout();
dog.sayInfo();
cat.sayInfo();
</script>
</body>
</html> |
其实也是一个函数的数组来作为公用的方法,直接可以调用的函数当做“静态方法”。
JQUERY的插件实现也用到了类似的方法,源码中jQuery.fn = jQuery.prototype={…},对jQuery类的prototype和jQuery.fn指向同一个对象。在我们开发插件的时候jQuery.fn.yourName = function() {} 就有点继承的感觉了。
看起来有点头疼。。。。
第一个例子里面的连接:
点击之后IE7会报错…FF和chrome没反应…
第二个没看懂,因为没学习过JAVA….
o(╯□╰)o
点击测试调用私有方法报错是正常的,后面说了,这是尝试调用对象的私有方法,是不被允许的。