JavaScript面向对象编程(2)

 

继承 和 重载

通过上面的那些示例,我们可以通过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'},
  8. 'website': { value: 'http://coolshell.cn'}
  9. }
  10. );
  11. Person.sayHello = function () {
  12. var hello = "<p>Hello, I am "+ this.name + ", <br>" +
  13. "my email is: " + this.email + ", <br>" +
  14. "my website is: " + this.website;
  15. document.write(hello + "<br>");
  16. }
  17. var Student = Object.create(Person);
  18. Student.no = "1234567"; //学号
  19. Student.dept = "Computer Science"; //系
  20. //使用Person的属性
  21. document.write(Student.name + ' ' + Student.email + ' ' + Student.website +'<br>');
  22. //使用Person的方法
  23. Student.sayHello();
  24. //重载SayHello方法
  25. Student.sayHello = function (person) {
  26. var hello = "<p>Hello, I am "+ this.name + ", <br>" +
  27. "my email is: " + this.email + ", <br>" +
  28. "my website is: " + this.website + ", <br>" +
  29. "my student no is: " + this. no + ", <br>" +
  30. "my departent is: " + this. dept;
  31. document.write(hello + '<br>');
  32. }
  33. //再次调用
  34. Student.sayHello();
  35. //查看Student的属性(只有 no 、 dept 和 重载了的sayHello)
  36. document.write('<p>' + Object.keys(Student) + '<br>');

通用上面这个示例,我们可以看到,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 + ", <br>" +
  5. "my departent is: " + this. dept;
  6. document.write(hello + '<br>');
  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() + '<br>');
  19. document.write(Person.paint() + '<br>');
  20. Composition(Person, Sporter);
  21. document.write(Person.run() + '<br>');
  22. document.write(Person.swim() + '<br>');
  23. //看看 Person中有什么?(输出:sayHello,sing,paint,swim,run)
  24. document.write('<p>' + Object.keys(Person) + '<br>');

Prototype 和 继承

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

 
 
  1. var plus = function(x,y){
  2. document.write( x + ' + ' + y + ' = ' + (x+y) + '<br>');
  3. return x + y;
  4. };
  5. var minus = function(x,y){
  6. document.write(x + ' - ' + y + ' = ' + (x-y) + '<br>');
  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. c.calculate('+');
  14. c.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 + ", <br>" +
  8. "my email is: " + this.email + ", <br>" +
  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) + '<br>';
  26. hello += "my student no is: " + this. no + ", <br>" +
  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());

兼容性

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

本文中的所有代码都在Chrome最新版中测试过了。

下面是一些函数,可以用在不兼容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. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值