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 对象偷天换日。

    计划、执行、每天高效的活着学着
  • 相关阅读:
    一个提高N倍系统新能的编程点,却总是被普通开发们遗忘
    工作不到一年,做出了100k系统,老板给我升职加薪
    offer收割机也有方法论
    最长公共前缀
    罗马数字转整数
    回文数
    整数反转
    两数之和
    网页中Office和pdf相关文件导出
    搭建一个低配版的Mock Server
  • 原文地址:https://www.cnblogs.com/huxiaoyun90/p/4461853.html
Copyright © 2011-2022 走看看