zoukankan      html  css  js  c++  java
  • 【javascript 】组合式继承

    开发人员采用的js的继承结构

    function inheritPrototype(subType, superType) {
        var prototype = object(superType.prototype);
        prototype.constructor = subType;
        subType.prototype = prototype;
    }
    
    function obj() {
        function F() {}
        F.prototype = o;
        return new F();
    }
    function create(parent, test) {
        var f = obj(parent.prototype); //创建对象
        f.constructor = test; //增强对象
    }
    function Parent(name) {
        this.name = name;
        this.arr = ['brother', 'sister', 'parents'];
    }
    
    Parent.prototype.run = function() {
        return this.name;
    };
    
    function Child(name, age) {
        Parent.call(this, name);
        this.age = age;
    }
    inheritPrototype(Parent, Child); //通过这里实现继承
    var test = new Child('peter', 20);
    test.arr.push('new');
    console.log(test.arr); //brother,sister,parents,new
    console.log(test.run()); //只共享了方法
    var test2 = new Child('jack', 22);
    console.log(test2.arr); //引用问题解决
    
    
    关于call apply
    call(thisObj, Object); // call接收一个对象
    apply(thisObj, [argArray]) //apply接收一个数组
    call和apply可以用来改变函数中this的指向: 全选复制放进笔记 // 定义一个全局函数
    function f() {
        console.log(this.name);
    }
    // 定义一个全局变量
    var name = 'peter';
    var obj = {
        name: 'jack';
    };
    f.apply(window); //apple, 此时this 等于window  相当于window.f()
    f.apply(obj);
  • 相关阅读:
    P1744 采购特价商品
    P1359 租用游艇
    P3092 [USACO13NOV]没有找零No Change
    P1272 重建道路
    P2014 选课
    P1026 统计单词个数
    P1776 宝物筛选_NOI导刊2010提高(02)
    自定义异步非阻塞tornado框架
    tornado进阶篇
    tornado基础篇
  • 原文地址:https://www.cnblogs.com/airven/p/5350245.html
Copyright © 2011-2022 走看看