sheepiiHD
sheepiiHD

Reputation: 326

How do I call an object from an external javascript

For example:

Javascript File #1 - (index.js) The issue here is referencing the Object from Javascript File #2

function getTheObjectName(){
   var car = new Car("Cool car");
   console.log(car.getName()); //prints "cool car"
}

Javascript File #2 - (car.js)

class Car{
   constructor(name){
       this.name = name;
   }
   getName(){
      return this.name;
   }
}

I may have some syntax errors here, I'm not sure. But, I'm coming from Java, and C# where object calling "seems" simpler. I've searched the web, but perhaps, I'm asking the wrong question. Any assistance would be greatly appreciated.

Upvotes: 1

Views: 1342

Answers (3)

Garvit Khamesra
Garvit Khamesra

Reputation: 395

Hi you can you es6 features for it.

    class Car{
       constructor(name){
           this.name = name;
       }
       getName(){
          return this.name;
       }
    }
    export default Car;

file 2

import Car from './filename.js';
function getTheObjectName(){
   var car = new Car("Cool car");
   console.log(car.getName()); //prints "cool car"
}
getTheObjectName();

Upvotes: 1

Rut Shah
Rut Shah

Reputation: 1278

Include car.js first and then index.js.

Go to your html file and add below code and check.

Alternatively, if you want to have one consolidate javascript file then use a task manager like Gulp, Grunt etc and generate one bundle file which will be maintainable in long term.

Upvotes: 1

AnshulJS
AnshulJS

Reputation: 328

In the index.html file, put the files in this order.

    <script src="./car.js"></script>
    <script src="./index.js"></script>

Upvotes: 2

Related Questions