[关闭]
@cherishpeace 2014-07-13T13:13:18.000000Z 字数 15458 阅读 1319

javascript oo实现

很久很久以前,我还是个phper,第一次接触javascript觉得好神奇。跟传统的oo类概念差别很大。记得刚毕业面试,如何在javascript里面实现class一直是很热门的面试题,当前面试百度就被问到了,当年作为一个小白只是网上随便搜搜应付了下。= =现在发现当时知道的还是太少太少。今天整理了下javascript的oo实现,发现知道的越多,越发现知识真是无穷无尽。

原始时代最简单的oo实现

javascript虽然没有class的概念,但是它的函数却是可以new出来一个对象的。所以一个最简单的class就可以用function来模拟出来。

  1. function Animal(name){
  2. this.name = name;
  3. this.run = function(){
  4. console.log(this.name + "is running!!");
  5. }
  6. }
  7. var pet = new Animal("pet");
  8. pet.run();//petis running!!

这样 pet就有了属性,有了方法,不过这种写法毫无继承性,扩展性。比如我们要实现个dog类,只能把属性方法再写一遍。而且每个new出来的对象都有自己的方法,造成资源浪费。

在javascript里面有个原型链的概念,每一个函数都有一个prototype对象属性。这样通过这个函数new出来的对象会自动具有__proto__属性指向函数的prototype对象。说白了所有的实例对象都会共用一个prototype对象,并且调用一个属性或者方法时在自己上面找不到,就会找__proto__对象有没有,之后一直往上追溯一直到找到为止。具体表现为:

  1. function Animal(name){
  2. this.name = name;
  3. }
  4. Animal.prototype.run = function(){
  5. console.log(this.name + "is running!!");
  6. }
  7. var a = new Animal("a");
  8. var b = new Animal("b");
  9. console.log(Animal.prototype) //Animal {}
  10. console.log(Animal.prototype instanceof Object) //true prototype是个对象
  11. console.log(Animal.prototype.constructor == Animal)//true
  12. console.log(a.__proto__ == Animal.prototype) //true __proto__在new的时候会自动加载在实例对象上。在现代浏览器里可以看到
  13. console.log(b.__proto__ == Animal.prototype) //true
  14. console.log(a.__proto__.__proto__) //Object {} 最后会找到最上面的boject对象
  15. console.log(a.__proto__.run == a.run) //true
  16. console.log(a.__proto__.run == a.prototype.run) //true

所以,在prototype对象上定义的方法会被所有实例共享,这不就是复用吗?
于是有了基于原型链的继承的写法:

  1. function Animal(name){
  2. this.name = name;
  3. }
  4. Animal.prototype.run = function(){
  5. console.log(this.name + "is running!!");
  6. }
  7. function Dog(name){
  8. //调用父类的构造函数,通过改变this指向将属性赋值到新的实例对象
  9. Animal.call(this,name);
  10. }
  11. Dog.prototype = new Animal();
  12. var dog = new Dog("dog");
  13. dog.run();//dog is running!!

可以看到我们将Animal的实例对象暂且叫做a,作为 Dog的prototype,这样 Dog的实例对象dog的__proto__指向Dog的prototype也就是a,a的__proto__再指向Animal的prototype对象,这个对象上有run方法。于是我们调用dog.run()的时候会一层层的往上追溯一直找到run方法执行。于是通过原型链我们就让 Dog继承了Animal的方法run。

需要注意的是,如果在子类的prototype对象上也有run方法,就会覆盖父类的,因为查找时在自己上面就找到了,就不会向上回溯了。

上面是原型链方法的继承。而属性我们则是通过调用父类的构造函数来赋值的。因为属性不能所有的实例都公用,应该每个人都有自己的一份,所以不能放在原型上。

上面就是原始时代最简单的类继承了。

石器时代的oo实现

这个时代javascript变得比较重要了,作为非常有用的特性,oo开始被很多人研究。

首先上面的那种简单oo实现方式,其实是有很多问题的。
1.没有实现传统oo该有的super方法来调用父类方法。
作为oo,怎么能没有super呢。作为我们前端界宗师一般的人物。Douglas 有一篇经典文章。不过貌似有很多问题。国内的玉伯分析过。在这里

最后Douglas总结出来:

我编写 JavaScript 已经 8 个年头了,从来没有一次觉得需要使用 uber 方法。在类模式中,super 的概念相当重要;但是在原型和函数式模式中,super 的概念看起来是不必要的。现在回顾起来,我早期在 JavaScript 中支持类模型的尝试是一个错误。

2.直接将父类实例作为子类的原型,简单粗暴造成多余的原型属性。还有construct的问题。
这个问题主要是之前代码里面这一句造成的:

  1. Dog.prototype = new Animal();
  2. //var dog = new Dog("dog");
  3. //console.log(dog.__proto__) Animal {name: undefined}

执行new Animal()就会执行animal的构造函数,就会在Dog.prototype生成多余的属性值,这边是name。而一般属性值为了复用是不能放在原型对象上的。并且由于dog有自己的name属性,原型上的是多余的。

还有construct的问题。

  1. console.log(dog.constructor == Animal) //true
  2. console.log(dog.constructor == Dog) //false

显然这不是我们希望看到的。

所以我们要对上面做些改良:

  1. var F = function(){};
  2. F.prototype = Animal.prototype;
  3. Dog.prototype = new F();
  4. Dog.prototype.constructor = Dog;

我们可以封装下:

  1. function objCreate(prototype){
  2. var F = function(){};
  3. F.prototype = prototype;
  4. return new F();
  5. }
  6. function inherit(subclass,parentclass){
  7. subclass.prototype = objCreate(parentclass.prototype);
  8. subclass.prototype.constructor = subclass;
  9. }

于是继承可以写成:

  1. function Animal(name){
  2. this.name = name;
  3. }
  4. Animal.prototype.run = function(){
  5. console.log(this.name + "is running!!");
  6. }
  7. function Dog(name){
  8. //调用父类的构造函数,通过改变this指向将属性赋值到新的实例对象
  9. Animal.call(this,name);
  10. }
  11. inherit(Dog,Animal);
  12. var dog = new Dog("dog");
  13. dog.run();//dog is running!!

当年大学毕业面试,也就到这个程度了。 = =

工业时代的oo实现

这个时代,各种javascript类库像雨后春笋般涌现了出来。
上面最后给出的方案,使用起来还是很不便,比如需要自己手动维护在构造函数里调用父类构造函数。同时继承写法对不了接原理的比较容易出错。

这个时候涌现了一大堆的类库的实现:

1.首先有些类库决定跳出传统oo的思维。不一定非要实现传统oo的继承。归根到底我们是为了复用。于是出现了很多轻量级的复用方式。
比如jquery的extend:http://api.jquery.com/jQuery.extend/
还有kissy的mix:http://docs.kissyui.com/1.3/docs/html/api/seed/kissy/mix.html?highlight=mix#seed.KISSY.mix
还有kissy的argument:http://docs.kissyui.com/1.3/docs/html/api/seed/kissy/augment.html
还有很多很多,说白了都是对象级别上的混入达到复用的地步。大部分情况下已经足够了。

2.当然还是有人对类的继承有需求的。
下面我们看下kissy的extend的实现方式。其他类库实现方式类似,kissy的我觉得算是比较有代表性了。为了演示,做了些小修改。

  1. //这个就是我们之前实现的方法,为了演示做了些改动主要是处理了construct的问题
  2. function objCreate(prototypeconstruct){
  3. var F = function(){};
  4. F.prototype = prototype;
  5. var newPro = new F();
  6. newPro.construct = construct;//维护构造函数的改变
  7. return newPro;
  8. }
  9. //mix是个辅助方法,这边给个最简单的实现,其实kissy里面的复杂的多。这边不考虑深度遍历等等,只是最简单的实现。
  10. function mix(r, s) {
  11. for (var p in s) {
  12. if (s.hasOwnProperty(p)) {
  13. r[p] = s[p]
  14. }
  15. }
  16. }
  17. //下面是kissy的实现r代表子类 s代表父类,px代表最后会混入子类原型上的属性,sx代表会混入子类函数上面的属性,也就是可以当做静态方法。
  18. //http://docs.kissyui.com/1.3/docs/html/api/seed/kissy/extend.html?highlight=extend#seed.KISSY.extend
  19. function extend (r, s, px, sx) {
  20. if (!s || !r) {
  21. return r;
  22. }
  23. var sp = s.prototype,
  24. rp;
  25. //针对父类生成一个原型。跟之前我们写的一致
  26. rp = createObject(sp, r);
  27. //不是简单的直接复制原型对象,而是先把以前原型的方法跟要继承的合并之后再一起赋值
  28. r.prototype = S.mix(rp, r.prototype);
  29. //为子类增加superclass属性,指向一个父类对象,这样就可以调用父类的方法了。这边是实现比较巧妙的地方
  30. r.superclass = createObject(sp, s);
  31. //下面就是往原型还有函数上混入方法了
  32. // add prototype overrides
  33. if (px) {
  34. S.mix(rp, px);
  35. }
  36. // add object overrides
  37. if (sx) {
  38. S.mix(r, sx);
  39. }
  40. return r;
  41. }

有了kissy的extend我们可以这么用:

  1. function Animal(name){
  2. this.name = name;
  3. }
  4. Animal.prototype.run = function(){
  5. console.log(this.name + "is running!!");
  6. }
  7. function Dog(name){
  8. //Animal.call(this,name);
  9. //因为kissy的封装 这边可以这么用
  10. Dog.superclass.construct.call(this,name);
  11. }
  12. extend(Dog,Animal,{
  13. wang:function(){
  14. console.log("wang wang!!")
  15. }
  16. })
  17. var dog = new Dog("dog");
  18. dog.run();//dog is running!!
  19. dog.wang();//wang wang!!

相对之前的变得清晰了很多,也更易用了。

现代科技时代的oo实现

前面的写法,目前虽然还是有很多人用,不过也渐渐过时了。上面的写法还是不够清晰,定义属性,方法都很分散,也没有多继承,等特性。我们需要像传统oo一样具有一个类工厂,可以生成一个类,属性都定义在里面。同时具有继承的方法。

而随着javascript成为前端唯一的语言,一代代大神前仆后继。终于开始涌现出了各种神奇的写法,下面罗列下一些我觉得特别好的实现,加上原理注释。

John Resig的实现方式

作为jquery的作者。John Resig在博客里记录了一种class的实现,原文在此
调用方法:

  1. var Person = Class.extend({
  2. init: function(isDancing){
  3. this.dancing = isDancing;
  4. },
  5. dance: function(){
  6. return this.dancing;
  7. }
  8. });
  9. var Ninja = Person.extend({
  10. init: function(){
  11. this._super( false );
  12. },
  13. dance: function(){
  14. // Call the inherited version of dance()
  15. return this._super();
  16. },
  17. swingSword: function(){
  18. return true;
  19. }
  20. });
  21. var p = new Person(true);
  22. p.dance(); // => true
  23. var n = new Ninja();
  24. n.dance(); // => false
  25. n.swingSword(); // => true
  26. // Should all be true
  27. p instanceof Person && p instanceof Class &&
  28. n instanceof Ninja && n instanceof Person && n instanceof Class

源码解读:

  1. /* Simple JavaScript Inheritance
  2. * By John Resig http://ejohn.org/
  3. * MIT Licensed.
  4. */
  5. // Inspired by base2 and Prototype
  6. (function(){
  7. //initializing是为了解决我们之前说的继承导致原型有多余参数的问题。当我们直接将父类的实例赋值给子类原型时。是会调用一次父类的构造函数的。所以这边会把真正的构造流程放到init函数里面,通过initializing来表示当前是不是处于构造原型阶段,为true的话就不会调用init。
  8. //fnTest用来匹配代码里面有没有使用super关键字。对于一些浏览器`function(){xyz;}`会生成个字符串,并且会把里面的代码弄出来,有的浏览器就不会。`/xyz/.test(function(){xyz;})`为true代表浏览器支持看到函数的内部代码,所以用`/\b_super\b/`来匹配。如果不行,就不管三七二十一。所有的函数都算有super关键字,于是就是个必定匹配的正则。
  9. var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  10. // The base Class implementation (does nothing)
  11. // 超级父类
  12. this.Class = function(){};
  13. // Create a new Class that inherits from this class
  14. // 生成一个类,这个类会具有extend方法用于继续继承下去
  15. Class.extend = function(prop) {
  16. //保留当前类,一般是父类的原型
  17. //this指向父类。初次时指向Class超级父类
  18. var _super = this.prototype;
  19. // Instantiate a base class (but only create the instance,
  20. // don't run the init constructor)
  21. //开关 用来使原型赋值时不调用真正的构成流程
  22. initializing = true;
  23. var prototype = new this();
  24. initializing = false;
  25. // Copy the properties over onto the new prototype
  26. for (var name in prop) {
  27. // Check if we're overwriting an existing function
  28. //这边其实就是很简单的将prop的属性混入到子类的原型上。如果是函数我们就要做一些特殊处理
  29. prototype[name] = typeof prop[name] == "function" &&
  30. typeof _super[name] == "function" && fnTest.test(prop[name]) ?
  31. (function(name, fn){
  32. //通过闭包,返回一个新的操作函数.在外面包一层,这样我们可以做些额外的处理
  33. return function() {
  34. var tmp = this._super;
  35. // Add a new ._super() method that is the same method
  36. // but on the super-class
  37. // 调用一个函数时,会给this注入一个_super方法用来调用父类的同名方法
  38. this._super = _super[name];
  39. // The method only need to be bound temporarily, so we
  40. // remove it when we're done executing
  41. //因为上面的赋值,是的这边的fn里面可以通过_super调用到父类同名方法
  42. var ret = fn.apply(this, arguments);
  43. //离开时 保存现场环境,恢复值。
  44. this._super = tmp;
  45. return ret;
  46. };
  47. })(name, prop[name]) :
  48. prop[name];
  49. }
  50. // 这边是返回的类,其实就是我们返回的子类
  51. function Class() {
  52. // All construction is actually done in the init method
  53. if ( !initializing && this.init )
  54. this.init.apply(this, arguments);
  55. }
  56. // 赋值原型链,完成继承
  57. Class.prototype = prototype;
  58. // 改变constructor引用
  59. Class.prototype.constructor = Class;
  60. // 为子类也添加extend方法
  61. Class.extend = arguments.callee;
  62. return Class;
  63. };
  64. })();

相当简单高效的实现方式,super的实现方式非常亮

P.js的实现

源地址:https://github.com/jneen/pjs
pjs的一大亮点是支持私有属性,他的类工厂传递的是函数不是对象。

调用方式:

  1. //可以生成一个可继承的对象,P接收一个函数,这个函数会传入生成后的class的原型。
  2. var Animal = P(function(animal) {
  3. animal.init = function(name) { this.name = name; };
  4. animal.move = function(meters) {
  5. console.log(this.name+" moved "+meters+"m.");
  6. }
  7. });
  8. //继承Animal。后面的snake,animal分别是前面Snake和Animal的原型。程序直接把这些对象暴露给你了。于是灵活度很高。
  9. var Snake = P(Animal, function(snake, animal) {
  10. snake.move = function() {
  11. console.log("Slithering...");
  12. animal.move.call(this, 5);
  13. };
  14. });
  15. var Horse = P(Animal, function(horse, animal) {
  16. //真正的私有属性,外面没法调用到
  17. var test = "hello world";
  18. horse.move = function() {
  19. console.log(test);
  20. console.log("Galloping...");
  21. //调用父类的方法,so easy!!
  22. animal.move.call(this, 45);
  23. };
  24. });
  25. //工厂方式生成对象,可以不用new
  26. var sam = Snake("Sammy the Python")
  27. , tom = Horse("Tommy the Palomino")
  28. ;
  29. sam.move()
  30. tom.move()

源码解读:

  1. var P = (function(prototype, ownProperty, undefined) {
  2. return function P(_superclass /* = Object */, definition) {
  3. // handle the case where no superclass is given
  4. if (definition === undefined) {
  5. definition = _superclass;
  6. _superclass = Object;
  7. }
  8. //最后返回的类就是这个,也就是我们需要的子类。这个类可以用new生成实例,也可以直接调用生成实例
  9. function C() {
  10. //判断,是new的话this instanceof C就是true。否则我们自己手动new一下Bare。Bare就是为了实现这种类工厂的生成类的方式
  11. var self = this instanceof C ? this : new Bare;
  12. self.init.apply(self, arguments);
  13. return self;
  14. }
  15. //这个就是用来实现不用new生成类的方式
  16. function Bare() {}
  17. C.Bare = Bare;
  18. //将父类的原型赋值给Bare
  19. //这边prototype就是个字符串“prototype”变量,主要为了压缩字节少点,所以作者还单独传成变量进来 = =
  20. var _super = Bare[prototype] = _superclass[prototype];
  21. //再生成这个空函数的实例赋值给C,Bare的原型,同时在C.p存下来
  22. //这样C,Bare都公用一个原型
  23. var proto = Bare[prototype] = C[prototype] = C.p = new Bare;
  24. var key;
  25. //改变constructor指向
  26. proto.constructor = C;
  27. //上面几部其实还是实现的通用的继承实现方式,新建个空函数,将父类的原型赋给这个空函数再生成实例赋值给子类的原型。万变不离其宗。原理都一样
  28. //增加extend方法。这是个语法糖,本质上还是调用P来实现,只不过第一个参数是调用者C
  29. C.extend = function(def) { return P(C, def); }
  30. //下面是最关键的地方,写的有点绕。这边分为这几步
  31. //传入definition 执行 function(def){}
  32. // 执行C.open = C
  33. // return C.open 其实就是 renturn C 返回最终的生成类
  34. return (C.open = function(def) {
  35. if (typeof def === 'function') {
  36. // call the defining function with all the arguments you need
  37. // extensions captures the return value.
  38. //是函数的话就传入 一些属性包括子类原型,父类原型,子类构造函数,父类构造函数
  39. def = def.call(C, proto, _super, C, _superclass);
  40. }
  41. // 如果是对象,就直接混入到原型
  42. if (typeof def === 'object') {
  43. for (key in def) {
  44. if (ownProperty.call(def, key)) {
  45. proto[key] = def[key];
  46. }
  47. }
  48. }
  49. //确保有init函数
  50. if (!('init' in proto)) proto.init = _superclass;
  51. return C;
  52. })(definition);
  53. }
  54. })('prototype', ({}).hasOwnProperty);

阿拉蕾的实现方式

这是支付宝的库阿拉蕾的实现,我觉得是最不错的一种方式:
源地址:https://github.com/aralejs/class/blob/master/class.js

  1. // The base Class implementation.
  2. function Class(o) {
  3. //这个判断用来支持 将一个已有普通类转换成 阿拉蕾的类
  4. if (!(this instanceof Class) && isFunction(o)) {
  5. //原理是给这个函数增加extend,implement方法
  6. return classify(o)
  7. }
  8. }
  9. //用来支持 commonjs的模块规范。
  10. module.exports = Class
  11. // Create a new Class.
  12. //
  13. // var SuperPig = Class.create({
  14. // Extends: Animal,
  15. // Implements: Flyable,
  16. // initialize: function() {
  17. // SuperPig.superclass.initialize.apply(this, arguments)
  18. // },
  19. // Statics: {
  20. // COLOR: 'red'
  21. // }
  22. // })
  23. //
  24. //
  25. //用于创建一个类,
  26. //第一个参数可选,可以直接创建时就指定继承的父类。
  27. //第二个参数也可选,用来表明需要混入的类属性。有三个特殊的属性为Extends,Implements,Statics.分别代表要继承的父类,需要混入原型的东西,还有静态属性。
  28. Class.create = function(parent, properties) {
  29. //创建一个类时可以不指定要继承的父类。直接传入属性对象。
  30. if (!isFunction(parent)) {
  31. properties = parent
  32. parent = null
  33. }
  34. properties || (properties = {})
  35. //没有指定父类的话 就查看有没有Extends特殊属性,都没有的话就用Class作为父类
  36. parent || (parent = properties.Extends || Class)
  37. properties.Extends = parent
  38. // 子类构造函数的定义
  39. function SubClass() {
  40. // 自动帮忙调用父类的构造函数
  41. parent.apply(this, arguments)
  42. // Only call initialize in self constructor.
  43. //真正的构造函数放在initialize里面
  44. if (this.constructor === SubClass && this.initialize) {
  45. this.initialize.apply(this, arguments)
  46. }
  47. }
  48. // Inherit class (static) properties from parent.
  49. //parent为Class就没必要混入
  50. if (parent !== Class) {
  51. //将父类里面的属性都混入到子类里面这边主要是静态属性
  52. mix(SubClass, parent, parent.StaticsWhiteList)
  53. }
  54. // Add instance properties to the subclass.
  55. //调用implement将自定义的属性混入到子类原型里面。遇到特殊值会单独处理,真正的继承也是发生在这里面
  56. //这边把属性也都弄到了原型上,因为这边每次create或者extend都会生成一个新的SubClass。所以倒也不会发生属性公用的问题。但是总感觉不大好
  57. implement.call(SubClass, properties)
  58. // Make subclass extendable.
  59. //给生成的子类增加extend和implement方法,可以在类定义完后,再去继承,去混入其他属性。
  60. return classify(SubClass)
  61. }
  62. //用于在类定义之后,往类里面添加方法。提供了之后修改类的可能。类似上面defjs实现的open函数。
  63. function implement(properties) {
  64. var key, value
  65. for (key in properties) {
  66. value = properties[key]
  67. //发现属性是特殊的值时,调用对应的处理函数处理
  68. if (Class.Mutators.hasOwnProperty(key)) {
  69. Class.Mutators[key].call(this, value)
  70. } else {
  71. this.prototype[key] = value
  72. }
  73. }
  74. }
  75. // Create a sub Class based on `Class`.
  76. Class.extend = function(properties) {
  77. properties || (properties = {})
  78. //定义继承的对象是自己
  79. properties.Extends = this
  80. //调用Class.create实现继承的流程
  81. return Class.create(properties)
  82. }
  83. //给一个普通的函数 增加extend和implement方法。
  84. function classify(cls) {
  85. cls.extend = Class.extend
  86. cls.implement = implement
  87. return cls
  88. }
  89. // 这里定义了一些特殊的属性,阿拉蕾遍历时发现key是这里面的一个时,会调用这里面的方法处理。
  90. Class.Mutators = {
  91. //这个定义了继承的真正操作代码。
  92. 'Extends': function(parent) {
  93. //这边的this指向子类
  94. var existed = this.prototype
  95. //生成一个中介原型,就是之前我们实现的objectCreat
  96. var proto = createProto(parent.prototype)
  97. //将子类原型有的方法混入到新的中介原型上
  98. mix(proto, existed)
  99. // 改变构造函数指向子类
  100. proto.constructor = this
  101. // 改变原型 完成继承
  102. this.prototype = proto
  103. //为子类增加superclass属性,这样可以调用父类原型的方法。
  104. this.superclass = parent.prototype
  105. },
  106. //这个有点类似组合的概念,支持数组。将其他类的属性混入到子类原型上
  107. 'Implements': function(items) {
  108. isArray(items) || (items = [items])
  109. var proto = this.prototype, item
  110. while (item = items.shift()) {
  111. mix(proto, item.prototype || item)
  112. }
  113. },
  114. //传入静态属性
  115. 'Statics': function(staticProperties) {
  116. mix(this, staticProperties)
  117. }
  118. }
  119. // Shared empty constructor function to aid in prototype-chain creation.
  120. function Ctor() {
  121. }
  122. // 这个方法就是我们之前实现的objectCreat,用来使用一个中介者来处理原型的问题,当浏览器支持`__proto__`时可以直接使用。否则新建一个空函数再将父类的原型赋值给这个空函数,返回这个空函数的实例
  123. var createProto = Object.__proto__ ?
  124. function(proto) {
  125. return { __proto__: proto }
  126. } :
  127. function(proto) {
  128. Ctor.prototype = proto
  129. return new Ctor()
  130. }
  131. // Helpers 下面都是些辅助方法,很简单就不说了
  132. // ------------
  133. function mix(r, s, wl) {
  134. // Copy "all" properties including inherited ones.
  135. for (var p in s) {
  136. //过滤掉原型链上面的属性
  137. if (s.hasOwnProperty(p)) {
  138. if (wl && indexOf(wl, p) === -1) continue
  139. // 在 iPhone 1 代等设备的 Safari 中,prototype 也会被枚举出来,需排除
  140. if (p !== 'prototype') {
  141. r[p] = s[p]
  142. }
  143. }
  144. }
  145. }
  146. var toString = Object.prototype.toString
  147. var isArray = Array.isArray || function(val) {
  148. return toString.call(val) === '[object Array]'
  149. }
  150. var isFunction = function(val) {
  151. return toString.call(val) === '[object Function]'
  152. }
  153. var indexOf = Array.prototype.indexOf ?
  154. function(arr, item) {
  155. return arr.indexOf(item)
  156. } :
  157. function(arr, item) {
  158. for (var i = 0, len = arr.length; i < len; i++) {
  159. if (arr[i] === item) {
  160. return i
  161. }
  162. }
  163. return -1
  164. }

万变不离其宗,本质上还是我们之前的继承方式,只是在上面再封装一层,更加清晰,明白了。
还有很多很多的实现,这边就不一一列举了。

未来科技的oo实现

其实 es6已经开始重视emcsript的oo实现了。不过还没定案,就算定案了,也不知道嘛时候javascript会实现。再加上一大堆浏览器的跟进。不知道什么时候才能用的上。不过了解下最新的规范还是很有必要的。

目前nodejs里面已经实现了 inherite方法用来实现类继承,类似我们上面的那种实现。

而es6(harmony)实现了class关键字用来创建类,并且具有类该有的一系列方法。如下:

  1. class Monster {
  2. // The contextual keyword "constructor" followed by an argument
  3. // list and a body defines the body of the class’s constructor
  4. // function. public and private declarations in the constructor
  5. // declare and initialize per-instance properties. Assignments
  6. // such as "this.foo = bar;" also set public properties.
  7. constructor(name, health) {
  8. public name = name;
  9. private health = health;
  10. }
  11. // An identifier followed by an argument list and body defines a
  12. // method. A “method” here is simply a function property on some
  13. // object.
  14. attack(target) {
  15. log('The monster attacks ' + target);
  16. }
  17. // The contextual keyword "get" followed by an identifier and
  18. // a curly body defines a getter in the same way that "get"
  19. // defines one in an object literal.
  20. get isAlive() {
  21. return private(this).health > 0;
  22. }
  23. // Likewise, "set" can be used to define setters.
  24. set health(value) {
  25. if (value < 0) {
  26. throw new Error('Health must be non-negative.')
  27. }
  28. private(this).health = value
  29. }
  30. // After a "public" modifier,
  31. // an identifier optionally followed by "=" and an expression
  32. // declares a prototype property and initializes it to the value
  33. // of that expression.
  34. public numAttacks = 0;
  35. // After a "public" modifier,
  36. // the keyword "const" followed by an identifier and an
  37. // initializer declares a constant prototype property.
  38. public const attackMessage = 'The monster hits you!';
  39. }

可以看到具有了传统oo里面的大部分关键字,私有属性也得到了支持。

继承也很容易:

  1. class Base {}
  2. class Derived extends Base {}
  3. //Here, Derived.prototype will inherit from Base.prototype.
  4. let parent = {};
  5. class Derived prototype parent {}

原文在这里:http://h3manth.com/content/classes-javascript-es6

结语

虽然es6已经实现了正规的class关键字。不过等到真正能用上也不知道是何年马月了。不过规范提供了方向,在es6还没出来之前,n多大神前仆后继实现了自己的class方式,分析源码可以学到的还是很多,仅仅一个类的实现就可以抠出这么多的类容,程序员还是应该多探索,不能只停留在表面。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注