【javascript】继承

1. js 其实是一个非面向对象的语言,通过对象的深浅复制完成继承

 

2. 继承方法

继承的方法有两种

1)prototype 原型模式

举个例子

var Animal = function () {
    this.type = 'animal';
    this.tmp = {name:'hehe'};
    this.eat = function (tmp) {
        console.log('animal eat');
    };
    this.modifyTmp = function (tmp) {
        this.tmp.name = tmp;
    }
}

var Cat = function (name) {
    this.type = 'cat';
    this.name = name;
    this.eat = function () {
        console.log('cat eat:' + this.name);
    }
}

Cat.prototype = new Animal();

var cat1 = new Cat('cat1');
cat1.eat();
cat1.modifyTmp('lala');
console.log(cat1.tmp);  // 输出 lala

var cat2 = new Cat('cat2');
cat2.eat();
console.log(cat2.tmp); // 输出lala
View Code

 

注意:此处有坑!!

为什么通过原型继承输出的都是 lala 呢?

因为此时的 tmp 的类型为对象 或者 array, 当进行 prototype 继承时, 实际是通过对象引用完成继承,此时 cat1  cat2 都是指向同一个Animal 对象。如果tmp 为基础类型(string,int)时,不存在引用,可以无需担心。

可以将 tmp 重新定义给外部 cat1 cat2 对象,进行重新复制,将会指向两个不同对象,例子如下:

var Animal = function () {
    this.type = 'animal';
    this.tmp = {name:'hehe'};
    this.eat = function (tmp) {
        console.log('animal eat');
    };
    this.modifyTmp = function (tmp) {
        this.tmp.name = tmp;
        return this.tmp;
    }
}

var Cat = function (name) {
    this.type = 'cat';
    this.name = name;
    this.tmp = {};
    this.eat = function () {
        console.log('cat eat:' + this.name);
        this.tmp = this.tmp;
    }
}

Cat.prototype = new Animal();

var cat1 = new Cat('cat1');
cat1.eat();
cat1.tmp = cat1.modifyTmp('lala');
console.log('cat1',cat1); // lala

var cat2 = new Cat('cat2');
cat2.eat();
cat2.tmp = cat2.modifyTmp('miaomiao');
console.log('cat2:',cat2); // miaomiao
console.log('cat1',cat1); // lala
View Code

 

2) call apply 方式

这个是利用this 对象偷天换日。

 

posted @ 2015-04-28 00:12  空城夕  阅读(155)  评论(0编辑  收藏  举报