javascript 继承

来源:互联网 发布:人工智能中英文介绍 编辑:程序博客网 时间:2024/05/16 19:17
<script>var deepClone = function(source,target){    source = source || {} ;    var toStr = Object.prototype.toString ,        arrStr = '[object array]' ;    for(var i in source){        if(source.hasOwnProperty(i)){            var item = source[i] ;            if(typeof item === 'object'){                target[i] = (toStr.apply(item).toLowerCase() === arrStr) ? [] :  {} ;                deepClone(item,target[i]) ;                }else{                target[i] = item;            }        }    }    return target ;} ;var extend = function(Parent,Child){    Child = Child || function(){} ;    if(Parent === undefined)        return Child ;    //借用父类构造函数    _Child = function(){        Parent.apply(this,arguments) ;        Child.apply(this,arguments);    } ;    //通过深拷贝继承父类原型        _Child.prototype = deepClone(Parent.prototype,_Child.prototype) ;    //重置constructor属性    _Child.prototype.constructor = Child ;    return _Child;} ;var Parent = function(name){    this.name = name || 'parent' ;} ;Parent.prototype.getName = function(){    return this.name ;} ;Parent.prototype.obj = {a : 1} ;var Child = function(name){    this.childName = name;} ;Child = extend(Parent,Child);var parent = new Parent('myParent') ;var child = new Child('myChild') ;console.log(child.obj.a)</script>

0 0