Satyaaditya
Satyaaditya

Reputation: 595

use a class from another class which is in another file in ES6

i am trying to use ES6 in a project which is previously written in es5

requirement :

i have class Abc in file1.js and class Def in file2.js , how can i instantiate class Abc from Def in javascript ES6 and use its methods?

sample demo: file1.js

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

file 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();

it would be great help if anyone share good resources on ES6 , as i saw sites such as mdn but want to read articles which focus on good usage examples

Upvotes: 0

Views: 588

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

If you want to import something in one file you will have to export it in another file.

In your file1.js add the following code:

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

If you have multiple classes in that file, you can also export them like in the example above:

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;
  }
}

and then import them like this in file2.js:

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

Upvotes: 1

Bergi
Bergi

Reputation: 664297

You're missing an export declaration:

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

Upvotes: 1

Related Questions