Click here to Skip to main content
16,022,309 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am working with javascript implementation, in which there it two class based javascript file namely Product and Order, i want to load the product js file by Order js file and start executing the all functionality from product file. but unable to do this, please help,
please see below code;

following error coming:

ERROR
Product is not defined


What I have tried:

product.js file:
JavaScript
class Product {
    constructor() {

    }
    getProducts() {
        return "all product will retur from here";
    }
}


order.js file
class Order {
    constructor() {

    }
    loadProductScript() {
        $("head").append(
            $("<script>")
                .attr("src",'/Product.js').attr("type", "text/javascript")
                .on("load", function () {
                })
        );
    }
    getOrders() {
        return "all data will return from this method";
    }
}


html file content

<script src="baseAddress/order.js"></script>


<script>
let order=new Order();
order.loadProductScript();
    let product=new Product();
    product.getProducts();
</script>
Posted
Updated 30-May-24 7:16am
v3

1 solution

You need to include all of the required scripts, in the correct order, before you can use them. Since order.js depends on product.js, you need to add:
HTML
<script src="baseAddress/product.js"></script>
<script src="baseAddress/order.js"></script>
Alternatively, you can rewrite your scripts as JavaScript modules[^], which would allow the scripts to declare their dependencies up-front. But note the limits on cross-browser compatibility mentioned in the MDN article.

product.js:
JavaScript
class Product {
    constructor() {

    }
    getProducts() {
        return "all product will retur from here";
    }
}

export { Product };
order.js:
JavaScript
import { Product } from "./product.js";

class Order {
    constructor() {

    }
    getOrders() {
        return "all data will return from this method";
    }
}

export { Order };
main.js:
JavaScript
import { Product } from "./product.js";
import { Order } from "./order.js";

let order = new Order();
let product = new Product();
product.getProducts();
...
HTML file:
HTML
<script type="module" src="baseAddress/main.js"></script>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900