详解js中extend函数
来源:互联网 发布:澳门网络真人赌博游戏 编辑:程序博客网 时间:2024/05/16 10:16
extend详解
为了简化类的声明,可以把派生子类的整个过程包装在一个extend的函数,和其他语言中的extend关键字类似,基于一个给定的类结构创建一个新的类
function extend(subClass, superClass){ var F = function(){ }; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; }
这样和原型链继承中直接使用subClass.prototype = new superClass()有什么区别呢,作为一项改进,它添加了一个空函数F,并将它创建的对象添加进原型链中,这样可以避免产生superClass的新实例,因为它可能比较庞大。下面是extend函数的使用场景:
function Person(name){ this.name = name; } Person.prototype.getName = function(){ return this.name; } function Author(name, books){ //执行Person构造函数,获得Person对象中属性 Person.call(this, name); this.books = books; } //获得Person原型上的方法,实现原型继承 extend(Author, Person); //在Author原型上继续添加我们需要的方法 Author.prototype.getBooks = function(){ return this.books; }
extend的改进
这样唯一的缺点是在Author构造函数中还出现了Person,耦合程度太高,所以我们需要对extend函数做一些改进
function extend(subClass, superClass){ var F = function(){ }; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; subClass.superclass = superClass.prototype; //修正原型的constructor指向 if(!superClass.prototype.contrucotor == Object.prototype.constructor){ superClass.prototype.constructor = superClass; } } //使用中 function Author(name, books){ //从superClass.constructor中调用 Author.superClass.constructor.call(this, name) this.books = books; } //获得Person原型上的方法,实现原型继承 extend(Author, Person);
clone函数
与基于类的继承不同,还有一种基于对象的原型式继承,不需要构造函数
var obj = { name: 'sysuzhyupeng', say: function(){ alert(1); } } var newObj = clone(obj); newObj.name // 'sysuzhyupeng'
来看一下clone函数的源码:
function clone(object){ function F(){} F.prototype = object; return new F; }
clone函数所返回的是一个以给定对象为原型对象的空对象
0 0
- 详解js中extend函数
- jQuery中extend函数详解
- 神奇的js,jQuery.extend 函数详解
- $.extend,jQuery.extend 函数详解
- js 自定义extend函数
- js 自定义extend函数
- js 插件开发代码示例 和 jQuery.extend 函数详解
- jQuery.extend 函数详解
- 详解Ext.extend 函数
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- jQuery.extend 函数详解
- 对并查集中的每一个节点的遍历问题(暴力方法)
- FATFS文件系统
- 蓝桥测试1->2015年第六届蓝桥杯省赛
- 1-vi编辑器与编译
- ios在同一个控制器中 动态显示和隐藏状态栏
- 详解js中extend函数
- 函数模板与类模板
- IntPtr是什么,该怎么用?
- 数学分析公式LaTex练习-洛必达法则
- node.js文件系统
- C# DataGridView 绑定 DataTable 正确用法
- Qt之translate、tr关系与中文问题详解
- Codeforces Round #395 (Div. 2)D
- java equals覆盖原则