js的子类继承父类

2016-12-03  本文已影响0人  GQ1994

在很多时候我们写的js操作都有很多的公用的地方,每次都去复制过来,代码复用性很差,为何不像java一样,将公共的一些操作,属性提取出来作为父类,然后子类去继承并继续做加工,不影响父类。

下面我来介绍下js的类的三种继承的写法

拷贝继承:(通用型的 有new或无new的时候都可以)

  1. 子类继承父类

     function ChildDrag(id) {   //子类
         Drag.call(this, id);//继承父类的属性
     }
    
     //继承父类的方法
     extend(ChildDrag.prototype, Drag.prototype);
    
     //子类重写父类的鼠标移动方法
     ChildDrag.prototype.fnMove = function (ev) {
    
         var L = ev.clientX - this.disX;
         var T = ev.clientY - this.disY;
    
         if (L < 0) {
             L = 0;
         }
         else if (L > document.documentElement.clientWidth - this.obj.offsetWidth) {
             L = document.documentElement.clientWidth - this.obj.offsetWidth;
         }
    
         this.obj.style.left = L + 'px';
         this.obj.style.top = T + 'px';
     };
    
     //for in 来继承父类的方法
     function extend(obj1, obj2) {
         for (var attr in obj2) {
             obj1[attr] = obj2[attr];
         }
     }
    

类似继承: (new构造函数)

JS是没有类的概念的 , 把JS中的构造函数看做的类

要做属性和方法继承的时候,要分开继承

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>

function Aaa(){   //父类
    this.name = [1,2,3];
}

Aaa.prototype.showName = function(){
    alert( this.name );
};

function Bbb(){   //子类
    Aaa.call(this);
}

var F = function(){};
F.prototype = Aaa.prototype;//利用空方法只继承父类的方法,不继承属性
Bbb.prototype = new F();//将继承来的方法给子类引用
Bbb.prototype.constructor = Bbb; //因为是从父类引用而来,所以要重新修正指向问题

var b1 = new Bbb();
//b1.showName();
//alert( b1.name );
//alert( b1.constructor );
b1.name.push(4);

var b2 = new Bbb();

alert( b2.name );

</script>
</head>

<body>
</body>
</html>

原型继承:(无new对象)

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <script>

        var a = {
            name: '小明'
        };

        var b = cloneObj(a);

        b.name = '小强';

        //alert( b.name );
        alert(a.name);

        function cloneObj(obj) {

            var F = function () {
            };

            F.prototype = obj;

            return new F();

        }

    </script>
</head>

<body>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读