如何将方法从一个类添加到另一个类的现有对象

时间:2019-04-20 19:22:29

标签: ecmascript-6 gulp babeljs es6-class rollupjs

我有一个大类,我将其分成两部分并将它们分别加载到页面上以提高性能。核心部分首先被同步加载,因为它包含关键功能,而扩展(非关键功能)则随后异步加载到页面中。

我只需要一个包含两个类功能的对象。但是在扩展加载时,已经有一个Core对象。如何将Extension中的功能添加到Core对象上?

我正在使用基于Gulp的资产管道

Rollup =将不同文件中的JS捆绑到一个文件中

Babel =将ES6转换为ES5

Uglify =最小化JS

这是我的目录结构:

js
|_ _classes
|   |_ ab.js
|   |_ cd.js
|_ core.js
|_ ext.js

我已将gulp构建任务设置为忽略“ _classes”目录中的文件。汇总分析“导入”语句以捆绑代码。

这就是我在core.js

中所拥有的
//core.js
import AB from './_classes/ab.js';

window.oab = new AB();

这是ext.js

//ext.js
import CD from './_classes/cd.js';

//let o_cd = new CD();

window.oab.prototype = CD;

这是核心课程

// file ab.js
class AB {

    constructor() {
        this.car = 'McLaren';
        this.fruit = 'Mango';
    }

    getCar() {
        return this.car;
    }

    getFruit() {
        return this.fruit;
    }

}

这是扩展类

//file cd.js
class CD {

    constructor() {
        this.plane = 'Gulfstream';
    }

    getPlane() {
        return this.plane;
    }

}

我正在尝试使它起作用:

console.log( window.oab.getCar() );  // prints McLaren
console.log( window.oab.getFruit() );  // prints Mango
console.log( window.oab.getPlane() );  // prints Gulfstream

现在,我可以很好地将AB类中的CD类导入,将CD类设置为扩展AB,这将给我我想要的东西。但是,使用我当前的gulp管道设置,这意味着Rollup还将将类AB的副本与类CD捆绑在一起,并且类AB早已加载。

由于汇总,Babel和Uglify,类名ABCD等不存在,因此我无法假设AB中的CD可用扩展而不先导入并导入它意味着将其与CD捆绑在一起。

1 个答案:

答案 0 :(得分:0)

我在ext.js的{​​{1}}中应用了猴子补丁,这给了我所需的信息。

window.oab

现在这有效

import CD from './_classes/cd.js';

( function() {

    let i;
    let ocd = new CD();
    let ocd_methods = Object.getOwnPropertyNames( ocd.__proto__ ).filter( p => {
        return ( 'function' === typeof ocd.__proto__[ p ] );
    });

    Object.assign( window.oab, ocd );   // this assigns only properties of ocd into window.oab and not the methods

    for ( i in ocd_methods ) {

        let method = ocd_methods[ i ];

        if ( '__proto__' === method || 'constructor' === method ) {
            continue;
        }

        window.oab.__proto__[ method ] = ocd[ method ];

    }

} () );
相关问题