zoukankan      html  css  js  c++  java
  • 【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 对象偷天换日。

    计划、执行、每天高效的活着学着
  • 相关阅读:
    Binder机制,从Java到C (大纲)
    大陆台湾计算机术语比对
    关于nginx架构探究(2)
    关于nginx架构探究(1)
    关于开源中文搜索引擎架构coreseek中算法详解
    关于linux定时操作cron的理解
    sqlachemy 使用实例
    nginx+uwsgi+flask搭建python-web应用程序
    VC维
    关于zMPLS的设计解析
  • 原文地址:https://www.cnblogs.com/huxiaoyun90/p/4461853.html
Copyright © 2011-2022 走看看