Yes.
Yes, javascript has classes and objects.
This is an example of making blockchain by using javascript/NodeJS classes and objects:-
// coded by Alfrick Opidi in Smashing Magazine blog
// https://www.smashingmagazine.com/2020/02/cryptocurrency-blockchain-node-js/
const SHA256 = require('crypto-js/sha256');
const fs = require('fs')
class CryptoBlock{
constructor(index, timestamp, data, precedingHash=" "){
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.precedingHash = precedingHash;
this.hash = this.computeHash();
}
computeHash(){
return SHA256(this.index + this.precedingHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class CryptoBlockchain{
constructor(){
this.blockchain = [this.startGenesisBlock()];
}
startGenesisBlock(){
return new CryptoBlock(0, "01/01/2020", "Initial Block in the Chain, its also called genisis", "0");
}
obtainLatestBlock(){
return this.blockchain[this.blockchain.length - 1];
}
addNewBlock(newBlock){
newBlock.precedingHash = this.obtainLatestBlock().hash;
newBlock.hash = newBlock.computeHash();
this.blockchain.push(newBlock);
}
}
let smashingCoin = new CryptoBlockchain();
smashingCoin.addNewBlock(new CryptoBlock(1, "01/06/2020", {sender: "Iris Ljesnjanin", recipient: "Cosima Mielke", quantity: 50}));
smashingCoin.addNewBlock(new CryptoBlock(2, "01/07/2020", {sender: "Vitaly Friedman", recipient: "Ricardo Gimenes", quantity: 100}) );
fs.writeFile('genisis.json', JSON.stringify(smashingCoin), function (err) {
if (err) throw err;
console.log('Saved!');
});
console.log(JSON.stringify(smashingCoin, null, 4));