设为首页收藏本站

Scripts 学盟

 找回密码
 加入学盟

QQ登录

只需一步,快速开始

查看: 1308|回复: 3
打印 上一主题 下一主题

Javascript 面向对象编程 [复制链接]

Rank: 8Rank: 8

风雨相伴

跳转到指定楼层
1#
Snail 实名认证  发表于 2012-4-5 09:20:00 |只看该作者 |倒序浏览
本帖最后由 Snail 于 2012-4-20 09:15 编辑

Javascript是一个类C的语言,它的面向对象的东西相对于C++/Java比较奇怪,但是其的确相当的强大,在Todd 同学的“对象的消息模型”一文中我们已经可以看到一些端倪了。这两天有个前同事总在问我Javascript面向对象的东西,所以,索性写篇文章让他看去吧,这里这篇文章主要想从一个整体的解度来说明一下Javascript的面向对象的编程。


我们知道Javascript中的变量定义基本如下:

  1. var name = \\\'Chen Hao\\\';;
  2. var email = \\\'haoel(@)hotmail.com\\\';
  3. var website = \\\'http://coolshell.cn\\\';
复制代码

如果要用对象来写的话,就是下面这个样子:

  1. var chenhao = {
  2.     name :\\\'Chen Hao\\\',
  3.     email : \\\'haoel(@)hotmail.com\\\',
  4.     website : \\\'http://coolshell.cn\\\'
  5. };
复制代码

于是,我就可以这样访问:

  1. //以成员的方式
  2. chenhao.name;
  3. chenhao.email;
  4. chenhao.website;

  5. //以hash map的方式
  6. chenhao[\\\"name\\\"];
  7. chenhao[\\\"email\\\"];
  8. chenhao[\\\"website\\\"];
复制代码

关于函数,我们知道Javascript的函数是这样的:

  1. var doSomething = function(){
  2.    alert(\\\'Hello World.\\\');
  3. };
复制代码

于是,我们可以这么干:

  1. var sayHello = function(){
  2.    var hello = \\\"Hello, I\\\'m \\\"+ this.name
  3.                 + \\\", my email is: \\\" + this.email
  4.                 + \\\", my website is: \\\" + this.website;
  5.    alert(hello);
  6. };

  7. //直接赋值,这里很像C/C++的函数指针
  8. chenhao.Hello = sayHello;

  9. chenhao.Hello();
复制代码

相信这些东西都比较简单,大家都明白了。 可以看到javascript对象函数是直接声明,直接赋值,直接就用了。runtime的动态语言。


还有一种比如规范的写法是:

  1. //我们可以看到, 其用function来做class。
  2. var Person = function(name, email, website){
  3.     this.name = name;
  4.     this.email = email;
  5.     this.website = website;

  6.     this.sayHello = function(){
  7.         var hello = \\\"Hello, I\\\'m \\\"+ this.name  + \\\", \\\\n\\\" +
  8.                     \\\"my email is: \\\" + this.email + \\\", \\\\n\\\" +
  9.                     \\\"my website is: \\\" + this.website;
  10.         alert(hello);
  11.     };
  12. };

  13. var chenhao = new Person(\\\"Chen Hao\\\", \\\"haoel@hotmail.com\\\",
  14.                                      \\\"http://coolshell.cn\\\");
  15. chenhao.sayHello();
复制代码

顺便说一下,要删除对象的属性,很简单:

  1. delete chenhao[\\\'email\\\']
复制代码

上面的这些例子,我们可以看到这样几点:


Javascript的数据和成员封装很简单。
Javascript function中的this指针很关键,如果没有的话,那就是局部变量或局部函数。
Javascript对象成员函数可以在使用时临时声明,并把一个全局函数直接赋过去就好了。
Javascript的成员函数可以在实例上进行修改,也就是说不同的实例的同一个函数名的行为和实现不一样。



属性配置 – Object.defineProperty


先看下面的代码:

  1. //创建对象
  2. var chenhao = Object.create(null);

  3. //设置一个属性
  4. Object.defineProperty( chenhao,
  5.                 \\\'name\\\', { value:  \\\'Chen Hao\\\',
  6.                           writable:     true,
  7.                           configurable: true,
  8.                           enumerable:   true });

  9. //设置多个属性
  10. Object.defineProperties( chenhao,
  11.     {
  12.         \\\'email\\\'  : { value:  \\\'haoel@hotmail.com\\\',
  13.                      writable:     true,
  14.                      configurable: true,
  15.                      enumerable:   true },
  16.         \\\'website\\\': { value: \\\'http://coolshell.cn\\\',
  17.                      writable:     true,
  18.                      configurable: true,
  19.                      enumerable:   true }
  20.     }
  21. );
复制代码

下面就说说这些属性配置是什么意思。


  • writable:这个属性的值是否可以改。
  • configurable:这个属性的配置是否可以改。
  • enumerable:这个属性是否能在for…in循环中遍历出来或在Object.keys中列举出来。
  • value:属性值。
  • get()/set(_value):get和set访问器。

Get/Set 选择器

关于get/set访问器,它的意思就是用get/set来取代value(其不能和value一起使用),示例如下:

  1. var  age = 0;
  2. Object.defineProperty( chenhao,
  3.             \\\'age\\\', {
  4.                       get: function() {return age+1;},
  5.                       set: function(value) {age = value;}
  6.                       enumerable : true,
  7.                       configurable : true
  8.                     }
  9. );
  10. chenhao.age = 100; //调用set
  11. alert(chenhao.age); //调用get 输出101;
复制代码

我们再看一个更为实用的例子——利用已有的属性(age)通过get和set构造新的属性(birth_year):

  1. Object.defineProperty( chenhao,
  2.             \\\'birth_year\\\',
  3.             {
  4.                 get: function() {
  5.                     var d = new Date();
  6.                     var y = d.getFullYear();
  7.                     return ( y - this.age );
  8.                 },
  9.                 set: function(year) {
  10.                     var d = new Date();
  11.                     var y = d.getFullYear();
  12.                     this.age = y - year;
  13.                 }
  14.             }
  15. );

  16. alert(chenhao.birth_year);
  17. chenhao.birth_year = 2000;
  18. alert(chenhao.age);
复制代码

这样做好像有点麻烦,你说,我为什么不写成下面这个样子:

  1. var chenhao = {
  2.     name: \\\"Chen Hao\\\",
  3.     email: \\\"haoel@hotmail.com\\\",
  4.     website: \\\"http://coolshell.cn\\\",
  5.     age: 100,
  6.     get birth_year() {
  7.         var d = new Date();
  8.         var y = d.getFullYear();
  9.         return ( y - this.age );
  10.     },
  11.     set birth_year(year) {
  12.         var d = new Date();
  13.         var y = d.getFullYear();
  14.         this.age = y - year;
  15.     }

  16. };
  17. alert(chenhao.birth_year);
  18. chenhao.birth_year = 2000;
  19. alert(chenhao.age);
复制代码

是的,你的确可以这样的,不过通过defineProperty()你可以干这些事:

1)设置如 writable,configurable,enumerable 等这类的属性配置。

2)动态地为一个对象加属性?比如:一些HTML的DOM对像。


查看对象属性配置


如果查看并管理对象的这些配置,下面有个程序可以输入这些东西:

  1. //列出对象的属性.
  2. function listProperties(obj)
  3. {
  4.     var newLine = \\\"\\\";
  5.     var names = Object.getOwnPropertyNames(obj);
  6.     for (var i = 0; i < names.length; i++) {
  7.         var prop = names[i];
  8.         document.write(prop + newLine);

  9.         // 列出对象的属性配置(descriptor)动用getOwnPropertyDescriptor函数。
  10.         var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  11.         for (var attr in descriptor) {
  12.             document.write(\\\"...\\\" + attr + \\\': \\\' + descriptor[attr]);
  13.             document.write(newLine);
  14.         }
  15.         document.write(newLine);
  16.     }
  17. }

  18. listProperties(chenhao);
复制代码

call,apply, bind 和 this


关于Javascript的this指针,和C++/Java很类似。 我们来看个示例:(这个示例很简单了,我就不多说了)

  1. function print(text){
  2.     document.write(this.value + \\\' - \\\' + text+ \\\'\\\');
  3. }

  4. var a = {value: 10, print : print};
  5. var b = {value: 20, print : print};

  6. print(\\\'hello\\\');// this => global, output \\\"undefined - hello\\\"

  7. a.print(\\\'a\\\');// this => a, output \\\"10 - a\\\"
  8. b.print(\\\'b\\\'); // this => b, output \\\"20 - b\\\"

  9. a[\\\'print\\\'](\\\'a\\\'); // this => a, output \\\"10 - a\\\"
复制代码

我们再来看看call 和 apply,这两个函数的差别就是参数的样子不一样,另一个就是性能不一样,apply的性能要差很多。(关于性能,可到 JSPerf 上去跑跑看看)

  1. print.call(a, \\\'a\\\'); // this => a, output \\\"10 - a\\\"
  2. print.call(b, \\\'b\\\'); // this => b, output \\\"20 - b\\\"

  3. print.apply(a, [\\\'a\\\']); // this => a, output \\\"10 - a\\\"
  4. print.apply(b, [\\\'b\\\']); // this => b, output \\\"20 - b\\\"
复制代码

但是在bind后,this指针,可能会有不一样,但是因为Javascript是动态的。如下面的示例

  1. var p = print.bind(a);
  2. p(\\\'a\\\');             // this => a, output \\\"10 - a\\\"
  3. p.call(b, \\\'b\\\');     // this => a, output \\\"10 - b\\\"
  4. p.apply(b, [\\\'b\\\']);  // this => a, output \\\"10 - b\\\"
复制代码
分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
分享分享0 收藏收藏0
命运的手,推我向前!何处是停歇!

Rank: 8Rank: 8

风雨相伴

2#
Snail 实名认证  发表于 2012-4-5 09:20:45 |只看该作者
本帖最后由 Snail 于 2012-4-20 09:13 编辑

继承 和 重载

通过上面的那些示例,我们可以通过Object.create()来实际继承,请看下面的代码,Student继承于Object。

  1. var Person = Object.create(null);

  2. Object.defineProperties
  3. (
  4.     Person,
  5.     {
  6.         \'name\'  : {  value: \'Chen Hao\'},
  7.         \'email\'  : { value : \'haoel@hotmail.com<script type=\"text/javascript\">
  8. /* <![CDATA[ */
  9. (function(){try{var s,a,i,j,r,c,l=document.getElementById(\"__cf_email__\");a=l.className;if(a){s=\'\';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
  10. /* ]]> */
  11. </script>\'},
  12.         \'website\': { value: \'http://coolshell.cn\'}
  13.     }
  14. );

  15. Person.sayHello = function (person) {
  16.     var hello = \"<p>Hello, I am \"+ this.name  + \", \" +
  17.                 \"my email is: \" + this.email + \", \" +
  18.                 \"my website is: \" + this.website;
  19.     document.write(hello + \"\");
  20. }

  21. var Student = Object.create(Person);
  22. Student.no = \"1234567\"; //学号
  23. Student.dept = \"Computer Science\"; //系

  24. //检查Person的属性
  25. document.write(Student.name + \' \' + Student.email + \' \' + Student.website +\'\');

  26. //检查Person的方法
  27. Student.sayHello();

  28. //重载SayHello方法
  29. Student.sayHello = function (person) {
  30.     var hello = \"<p>Hello, I am \"+ this.name  + \", \" +
  31.                 \"my email is: \" + this.email + \", \" +
  32.                 \"my website is: \" + this.website + \", \" +
  33.                 \"my student no is: \" + this. no + \", \" +
  34.                 \"my departent is: \" + this. dept;
  35.     document.write(hello + \'\');
  36. }
  37. //再次调用
  38. Student.sayHello();

  39. //查看Student的属性(只有 no 、 dept 和 重载了的sayHello)
  40. document.write(\'<p>\' + Object.keys(Student) + \'\');
复制代码

通用上面这个示例,我们可以看到,Person里的属性并没有被真正复制到了Student中来,但是我们可以去存取。这是因为Javascript用委托实现了这一机制。其实,这就是Prototype,Person是Student的Prototype。


当我们的代码需要一个属性的时候,Javascript的引擎会先看当前的这个对象中是否有这个属性,如果没有的话,就会查找他的Prototype对象是否有这个属性,一直继续下去,直到找到或是直到没有Prototype对象。


为了证明这个事,我们可以使用Object.getPrototypeOf()来检验一下:

  1. Student.name = \'aaa\';

  2. //输出 aaa
  3. document.write(\'<p>\' + Student.name + \'</p>\');

  4. //输出 Chen Hao
  5. document.write(\'<p>\' +Object.getPrototypeOf(Student).name + \'</p>\');
复制代码

于是,你还可以在子对象的函数里调用父对象的函数,就好像C++里的 Base::func() 一样。于是,我们重载hello的方法就可以使用父类的代码了,如下所示:

  1. //新版的重载SayHello方法
  2. Student.sayHello = function (person) {
  3.     Object.getPrototypeOf(this).sayHello.call(this);
  4.     var hello = \"my student no is: \" + this. no + \", \" +
  5.                 \"my departent is: \" + this. dept;
  6.     document.write(hello + \'\');
  7. }
复制代码

这个很强大吧。


组合

上面的那个东西还不能满足我们的要求,我们可能希望这些对象能真正的组合起来。为什么要组合?因为我们都知道是这是OO设计的最重要的东西。不过,这对于Javascript来并没有支持得特别好,不好我们依然可以搞定个事。


首先,我们需要定义一个Composition的函数:(target是作用于是对象,source是源对象),下面这个代码还是很简单的,就是把source里的属性一个一个拿出来然后定义到target中。

  1. function Composition(target, source)
  2. {
  3.     var desc  = Object.getOwnPropertyDescriptor;
  4.     var prop  = Object.getOwnPropertyNames;
  5.     var def_prop = Object.defineProperty;

  6.     prop(source).forEach(
  7.         function(key) {
  8.             def_prop(target, key, desc(source, key))
  9.         }
  10.     )
  11.     return target;
  12. }
复制代码

有了这个函数以后,我们就可以这来玩了:

  1. //艺术家
  2. var Artist = Object.create(null);
  3. Artist.sing = function() {
  4.     return this.name + \' starts singing...\';
  5. }
  6. Artist.paint = function() {
  7.     return this.name + \' starts painting...\';
  8. }

  9. //运动员
  10. var Sporter = Object.create(null);
  11. Sporter.run = function() {
  12.     return this.name + \' starts running...\';
  13. }
  14. Sporter.swim = function() {
  15.     return this.name + \' starts swimming...\';
  16. }

  17. Composition(Person, Artist);
  18. document.write(Person.sing() + \'\');
  19. document.write(Person.paint() + \'\');

  20. Composition(Person, Sporter);
  21. document.write(Person.run() + \'\');
  22. document.write(Person.swim() + \'\');

  23. //看看 Person中有什么?(输出:sayHello,sing,paint,swim,run)
  24. document.write(\'<p>\' + Object.keys(Person) + \'\');
复制代码

Prototype 和 继承


我们先来说说Prototype。我们先看下面的例程,这个例程不需要解释吧,很像C语言里的函数指针,在C语言里这样的东西见得多了。

  1. var plus = function(x,y){
  2.     document.write( x + \' + \' + y + \' = \' + (x+y) + \'\');
  3.     return x + y;
  4. };

  5. var minus = function(x,y){
  6.     document.write(x + \' - \' + y + \' = \' + (x-y) + \'\');
  7.     return x - y;
  8. };

  9. var operations = {
  10.     \'+\': plus,
  11.     \'-\': minus
  12. };

  13. var calculate = function(x, y, operation){
  14.     return operations[operation](x, y);
  15. };

  16. calculate(12, 4, \'+\');
  17. calculate(24, 3, \'-\');
复制代码

那么,我们能不能把这些东西封装起来呢,我们需要使用prototype。看下面的示例:

  1. var Cal = function(x, y){
  2.     this.x = x;
  3.     this.y = y;
  4. }

  5. Cal.prototype.operations = {
  6.     \'+\': function(x, y) { return x+y;},
  7.     \'-\': function(x, y) { return x-y;}
  8. };

  9. Cal.prototype.calculate = function(operation){
  10.     return this.operations[operation](this.x, this.y);
  11. };

  12. var c = new Cal(4, 5);

  13. Cal.calculate(\'+\');
  14. Cal.calculate(\'-\');
复制代码

这就是prototype的用法,prototype 是javascript这个语言中最重要的内容。网上有太多的文章介始这个东西了。说白了,prototype就是对一对象进行扩展,其特点在于通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的(当然,这里没有真正的复制,实际只是委托)。上面的这个例子中,我们扩展了实例Cal,让其有了一个operations的属性和一个calculate的方法。


这样,我们可以通过这一特性来实现继承。还记得我们最最前面的那个Person吧, 下面的示例是创建一个Student来继承Person。

  1. function Person(name, email, website){
  2.     this.name = name;
  3.     this.email = email;
  4.     this.website = website;
  5. };

  6. Person.prototype.sayHello = function(){
  7.     var hello = \"Hello, I am \"+ this.name  + \", \" +
  8.                 \"my email is: \" + this.email + \", \" +
  9.                 \"my website is: \" + this.website;
  10.     return hello;
  11. };

  12. function Student(name, email, website, no, dept){
  13.     var proto = Object.getPrototypeOf;
  14.     proto(Student.prototype).constructor.call(this, name, email, website);
  15.     this.no = no;
  16.     this.dept = dept;
  17. }

  18. // 继承prototype
  19. Student.prototype = Object.create(Person.prototype);

  20. //重置构造函数
  21. Student.prototype.constructor = Student;

  22. //重载sayHello()
  23. Student.prototype.sayHello = function(){
  24.     var proto = Object.getPrototypeOf;
  25.     var hello = proto(Student.prototype).sayHello.call(this) + \'\';
  26.     hello += \"my student no is: \" + this. no + \", \" +
  27.              \"my departent is: \" + this. dept;
  28.     return hello;
  29. };

  30. var me = new Student(
  31.     \"Chen Hao\",
  32.     \"haoel@hotmail.com\",
  33.     \"http://coolshell.cn\",
  34.     \"12345678\",
  35.     \"Computer Science\"
  36. );
  37. document.write(me.sayHello());
复制代码
命运的手,推我向前!何处是停歇!

使用道具 举报

Rank: 8Rank: 8

风雨相伴

3#
Snail 实名认证  发表于 2012-4-5 09:21:10 |只看该作者

兼容性

上面的这些代码并不一定能在所有的浏览器下都能运行,因为上面这些代码遵循 ECMAScript 5 的规范,关于ECMAScript 5 的浏览器兼容列表,你可以看这里“ES5浏览器兼容表”。


下面是一些函数,可以用在不兼容ES5的浏览器中:


Object.create()函数

  1. function clone(proto) {
  2.     function Dummy() { }

  3.     Dummy.prototype             = proto;
  4.     Dummy.prototype.constructor = Dummy;

  5.     return new Dummy(); //等价于Object.create(Person);
  6. }

  7. var me = clone(Person);
复制代码

defineProperty()函数

  1. function defineProperty(target, key, descriptor) {
  2.     if (descriptor.value){
  3.         target[key] = descriptor.value;
  4.     }else {
  5.         descriptor.get && target.__defineGetter__(key, descriptor.get);
  6.         descriptor.set && target.__defineSetter__(key, descriptor.set);
  7.     }

  8.     return target
  9. }
复制代码

keys()函数

  1. function keys(object) { var result, key
  2.     result = [];
  3.     for (key in object){
  4.         if (object.hasOwnProperty(key))  result.push(key)
  5.     }

  6.     return result;
  7. }
复制代码

Object.getPrototypeOf() 函数

  1. function proto(object) {
  2.     return !object?                null
  3.          : '__proto__' in object?  object.__proto__
  4.          : /* not exposed? */      object.constructor.prototype
  5. }
复制代码

bind 函数

  1. var slice = [].slice

  2. function bind(fn, bound_this) { var bound_args
  3.     bound_args = slice.call(arguments, 2)
  4.     return function() { var args
  5.         args = bound_args.concat(slice.call(arguments))
  6.         return fn.apply(bound_this, args) }
  7. }
复制代码


http://blog.jobbole.com/11691/
命运的手,推我向前!何处是停歇!

使用道具 举报

管理员

超级大菜鸟

Rank: 9Rank: 9Rank: 9

4#
混混@普宁.中国 实名认证  发表于 2012-4-5 09:55:34 |只看该作者
Snail 发表于 2012-4-5 09:21
兼容性
上面的这些代码并不一定能在所有的浏览器下都能运行,因为上面这些代码遵循 ECMAScript 5 的规范, ...

defineProperty 函数
木有看明白

使用道具 举报

您需要登录后才可以回帖 登录 | 加入学盟

手机版|Scripts 学盟   |

GMT+8, 2024-4-24 09:39 , Processed in 1.094899 second(s), 12 queries .

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部