javascript没有原生的继承语法,这确实很让人困惑,但是广大人民群从的智慧是无穷的。最近呢,正尝到一点从源码中学习的甜头,不分享一下实在难以平复激动的心情。前不久改造视频播放插件的时候,找到了videojs这个优秀的开源项目。经过一段时间深入学习它的源码,发现它的继承机制写的很好,而且短小精悍,于是决定把它拔离出来,做成一个单独的库,方便以后项目中使用。

//定义一个命名空间
var xut = {}; /**
* Core Object/Class for objects that use inheritance + contstructors
*
* @class
* @constructor
*/
xut.CoreObject = xut['CoreObject'] = function(){}; /**
* Create a new object that inherits from this Object
*
* var Animal = CoreObject.extend();
* var Horse = Animal.extend();
*
* @param {Object} props Functions and properties to be applied to the
* new object's prototype
* @return {xut.CoreObject} An object that inherits from CoreObject
* @this {*}
*/
xut.CoreObject.extend = function(props){
var init, subObj; props = props || {};
// Set up the constructor using the supplied init method
// or using the init of the parent object
// Make sure to check the unobfuscated version for external libs
init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){};
// In Resig's simple class inheritance (previously used) the constructor
// is a function that calls `this.init.apply(arguments)`
// However that would prevent us from using `ParentObject.call(this);`
// in a Child constuctor because the `this` in `this.init`
// would still refer to the Child and cause an inifinite loop.
// We would instead have to do
// `ParentObject.prototype.init.apply(this, argumnents);`
// Bleh. We're not creating a _super() function, so it's good to keep
// the parent constructor reference simple.
subObj = function(){
init.apply(this, arguments);
}; // Inherit from this object's prototype
subObj.prototype = xut.obj.create(this.prototype);
// Reset the constructor property for subObj otherwise
// instances of subObj would have the constructor of the parent Object
subObj.prototype.constructor = subObj; // Make the class extendable
subObj.extend = xut.CoreObject.extend;
// Make a function for creating instances
subObj.create = xut.CoreObject.create; // Extend subObj's prototype with functions and other properties from props
for (var name in props) {
if (props.hasOwnProperty(name)) {
subObj.prototype[name] = props[name];
}
} return subObj;
}; xut.obj = {}; xut.obj.create = Object.create || function(obj){
//Create a new function called 'F' which is just an empty object.
function F() {} //the prototype of the 'F' function should point to the
//parameter of the anonymous function.
F.prototype = obj; //create a new constructor function based off of the 'F' function.
return new F();
}; /**
* Create a new instace of this Object class
*
* var myAnimal = Animal.create();
*
* @return {xut.CoreObject} An instance of a CoreObject subclass
* @this {*}
*/
xut.CoreObject.create = function(){
// Create a new object that inherits from this object's prototype
var inst = xut.obj.create(this.prototype); // Apply this constructor function to the new object
this.apply(inst, arguments); // Return the new object
return inst;
};

项目地址:https://github.com/bjtqti/mini-extend

关于它的使用,我会抽空在git上详细说明,先作一个简单的案例,有兴趣的读者可以自行分析一下它的妙处:

var Animal = xut.CoreObject.extend({
init : function(name){
this.name = name;
}
}); Animal.prototype.getName = function(){
return this.name;
} Animal.prototype.makeSound = function(){
alert('xxx');
} var Bird = Animal.extend(); var Dog = Animal.extend({
makeSound : function(){
alert('wang...')
}
}); var b = new Bird('bage');
var d = new Dog('wang');
d.makeSound() b.makeSound()

子类可以很方便的继承父类的功能,而且子类也可以很自由的修改父类的功能,还不会影响它子类。这对于熟悉php/java等语言的程序员来说,这简直就是废话,但是js用这一百来行的代码实现,做到这种程度,非常的不容易。

javascript继承扩展类方法实现的更多相关文章

  1. 【读书笔记】javascript 继承

    在JavaScript中继承不像C#那么直接,C#中子类继承父类之后马上获得了父类的属性和方法,但JavaScript需要分步进行. 让Brid 继承 Animal,并扩展自己fly的方法. func ...

  2. javascript 继承、命名空间实现分享

    命名空间是用来组织和重用代码的编译单元,在大型项目开发中javascript使用的越来越多时,我们就应该将项目里的js类库管理起来,如何将自己进行归类管理,防止命名冲突,但是Javascript默认不 ...

  3. Javascript继承之最佳实践

    尊重原创,转载请注明出处:http://blog.csdn.net/zoutongyuan 什么是继承? 继承是面向对象最显著的一个特性.继承是从已有的类中派生出新的类,新的类能吸收已有类的数据属性和 ...

  4. JavaScript继承详解

    面向对象与基于对象 在传统面向对象的语言中,有两个非常重要的概念 - 类和实例. 类定义了一类事物公共的行为和方法:而实例则是类的一个具体实现. 我们还知道,面向对象编程有三个重要的概念 - 封装.继 ...

  5. JavaScript继承详解(五)

    在本章中,我们将分析John Resig关于JavaScript继承的一个实现 - Simple JavaScript Inheritance. John Resig作为jQuery的创始人而声名在外 ...

  6. javascript面向对象之Javascript 继承

    转自原文javascript面向对象之Javascript 继承 在JavaScript中实现继承可以有多种方法,下面说两种常见的. 一,call 继承 先定义一个“人”类 //人类 Person=f ...

  7. JavaScript 继承小记

    面向对象编程很重要的一个方面,就是对象的继承.A 对象通过继承 B 对象,就能直接拥有 B 对象的所有属性和方法.这对于代码的复用是非常有用的. 大部分面向对象的编程语言,都是通过“类”(class) ...

  8. javascript继承的三种模式

    javascript继承一般有三种模式:组合继承,原型式继承和寄生式继承: 1组合继承:javascript最为广泛的继承方式通过原型链实现对原型属性和方法的继承,通过构造函数实现对实例属性的继承,同 ...

  9. javascript继承机制的设计思想(ryf)

    我一直很难理解Javascript语言的继承机制. 它没有"子类"和"父类"的概念,也没有"类"(class)和"实例" ...

随机推荐

  1. [官方教程] [ES4封装教程]1.使用 VMware Player 创建适合封装的虚拟机

    [转载处,http://bbs.itiankong.com/] 前言: 首先要明确的一点,系统封装操作的源计算机一般为虚拟计算机(简称虚拟机.VM等),这也是为什么我们要在封装教程的第一章就专门学习虚 ...

  2. HLG2062(make,heap问题)

    最小的n个和 Time Limit: 1000 MS Memory Limit: 32768 K Total Submit: 129(37 users) Total Accepted: 35(29 u ...

  3. 数据结构与算法实验题7.1 M 商人的求救

    问题描述:A 国正面临着一场残酷的战争,城市被支持不同领导的两股势力占据,作为一个商人,M先生并不太关心政治,但是他知道局势很严重,他希望你能救他出去.M 先生说:“为了安全起见,我们的路线最多只能包 ...

  4. Balanced Teams (USACO Jan Bronze 2014)

    既然是bronze,毫无压力的AC了. 就是个深搜,当然加个剪枝--最后一个组不用搜. 恩可以一个一个组分层次dfs,这样会跑得飞起~~也不容易错 #include <cstdio> in ...

  5. object-c 继承多态 动态数据类型

    在c#中我们知道有继承的.同样在object-c中也有继承. 例如我们写一个人类(父),一个学生类.我们可以这么写: demo: @interface Person:NSobject{ NSStrin ...

  6. FastReport for delphi xe 安装步骤

    FastReport for delphi xe 安装步骤 1.先关闭DELPHI:2.下载后解压到一个目录,比如:D:FR:3.打开D:FR,运行recompile.exe ->点击" ...

  7. 【JAVA、C++】LeetCode 020 Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  8. JavaScript设计模式 - 迭代器模式

    迭代器模式是指提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示. 迭代器模式可以把迭代的过程从业务逻辑中分离出来,在使用迭代器模式之后,即使不关心对象的内部构造,也可以按顺 ...

  9. Python Elasticsearch api

    描述:ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.下面介绍了利用Python API接口进行数据查询,方便 ...

  10. 基因变异(codevs 3194)

    题目描述 Description 小毛终于来到了冥王星,这是一颗已经不属于行星的矮行星,它的表面温度低于-220度.在这里,小毛惊奇的发现,他带来的厌氧菌开始了基因变异,裂变的速度与光照时间(秒)成乘 ...