-2

I want to have a class that can CRUD. Have methods for each operation. Use the parameters that I mention in my class.

I was hoping I could use the parameters given to the constructor in my method. How can I do that?

I might need to use a dictionary or a list to store the data properly. Any advice?

const fs = require('fs')

class Product {
    constructor(productType, modelName, productPrice) {
        this.productType = productType;
        this.modelName = modelName;
        this.productPrice = productPrice;

    }

    oopWrite(productType, modelName, productPric) {
        const blah = [{productType, modelName, productPric}]//or use str arg;
        const dataJSON = JSON.stringify(blah)
        fs.writeFileSync('bleh.json', dataJSON);
        return dataJSON;
    }
}

const product1 = new Product();
console.log(product1.oopWrite({"productType":"Laptop"}, {"modelName":"ccc"}, {"modelName":"blah"}));

This class works without the constructor. How can I make the method use the parameters passed in the constructor?


Update to my Question -> I need to instantiate the Product as:

const blah = new Product{productType, modelName, productPrice}//or use str arg;
Kinfol
  • 55
  • 1
  • 9
  • Is this code running in a browser? Or is it running on a NodeJS server? – Code-Apprentice Nov 21 '19 at 23:33
  • Does this answer your question? [Is it possible to write data to file using only JavaScript?](https://stackoverflow.com/questions/21012580/is-it-possible-to-write-data-to-file-using-only-javascript) – Code-Apprentice Nov 21 '19 at 23:36
  • It doesn't really matter where the code is written. I am trying to write modular components that can be used in any scenario. There are plenty of examples on how to write to a file, but I couldn't find one that begins with a class. – Kinfol Nov 22 '19 at 07:39

1 Answers1

2

You are using readFileSync instead of writeFileSync

const fs = require('fs')

class Product {
    constructor({productType, modelName, productPrice}) {//use object parameter names
        this.productType = productType;
        this.modelName = modelName;
        this.productPrice = productPrice;

    }

    oopWrite() {
        const blah = [{this.productType, this.modelName, this.productPrice}]//pull from this;
        const dataJSON = JSON.stringify(blah)
        fs.writeFileSync('bleh.json', dataJSON);
        return dataJSON;
    }
}

const product1 = new Product({productType:"car", modelName:"porsch", productPrice:100000});
console.log(product1.oopWrite());//call without params
Sam Washington
  • 626
  • 4
  • 12
  • Thank you. The example you provided with works. I think I had something similar working. What I was hoping to get is instead of ```oopWrite(str) to have oopWrite(title, time) ``` so I can use parameters on the function later on when I instantiate the class I put the method in. Does that make sense. I posted the code last night, I guess I was dreaming. – Kinfol Nov 22 '19 at 07:41