javascript的几种继承方式

javascript继承

首先在开始之前,需要弄清楚prototype

Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。

意思就是每个对象都会有一个prototype属性,这个属性也是一个对象,默认是指向这个对象的 。如果prototype指向改变, prototype对象下面包含的属性和方法就会添加到指向的对象中,实现继承。

 

function Animal() {
            this.species = "动物";
        }
        function Cat(name, color) {
            this.name = name;
            this.color = color;
        }

        Cat.prototype = new Animal();
        Cat.prototype.constructor = Cat;
        var cat = new Cat("cat", "red");
        alert(cat.species);
 Cat.prototype = new Animal();//执行之前,Cat.prototype保存的是Cat的构造函数和它的属性,当指向改变时,Cat.prototype改变为Animal的构造函数和属性。
Cat.prototype.constructor = Cat;//这句话的意思是把Cat.prototype的构造函数重新复制给它。

利用空对象保存信息来中转:
function Animal() {
            
        }

        Animal.prototype.species = "动物";
       
        function Cat(name, color) {
            this.name = name;
            this.color = color;
        }

        var f = function () { };
        f.prototype = Animal.prototype;
        Cat.prototype = f.prototype;
        Cat.prototype.constructor = Cat;

yui库实现继承的方法

 function extend(parent,child) {
            var f = function () { };
            f.prototype = parent.prototype;
            child.prototype = new f();
            child.prototype.constructor = child;
            //child.uber = parent.prototype; uber向上 
        }

拷贝继承

 function extend1(parent,child) {
            var a = parent.prototype;
            var b = child.prototype;
            for (var i in a) {
                b[i] = a[i];
            }
        }

 

 

 

 

 

 

posted @ 2015-11-27 21:18  Bparadise  阅读(223)  评论(1编辑  收藏  举报