簡體   English   中英

使用另一個類中的類,該類位於 ES6 中的另一個文件中

[英]use a class from another class which is in another file in ES6

我正在嘗試在以前用 es5 編寫的項目中使用 ES6

要求 :

我在 file1.js 中有class Abc和在 file2.js 中有類Def ,我如何從 javascript ES6 中的Def實例化類Abc並使用它的方法?

示例演示:file1.js

class first{
constructor(a,b,c){
    this.a = a;
    this.b = b;
    this.c = c;
}
}

文件 2.js

import * as filee from  "/file1.js"
class def{
  method3(){
    let a = "satya";
    let b = "aditya";
    let c = function () {
        console.log("cr7");
    }
  let classs = new filee.first(a,b,c);
     classs.myMethod();
}
}
let a = new def();
a.method3();

如果有人在 ES6 上分享好的資源,那將是非常有幫助的,因為我看到了諸如 mdn 之類的網站,但想閱讀專注於良好使用示例的文章

如果您想在一個文件中導入某些內容,則必須將其導出到另一個文件中。

在您的file1.js添加以下代碼:

// vvv
export class first{
  constructor(a,b,c){
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

如果該文件中有多個類,您還可以像上面的示例一樣導出它們:

export class first{
  constructor(a,b,c){
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

export class second{
  constructor(a,b,c){
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

然后像這樣在file2.js導入它們:

import {first, second} from  "/file1.js"

您缺少出口申報單:

export class first { /*
^^^^^^ */
    …
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM