Answer the question
In order to leave comments, you need to log in
How to build a project in gulp+browserify so that you can create completely independent class objects at the end?
An application was developed, the output is the ability to create an object and work with it.
But here it was required to create a second object of this class on the same page, and I realized that I made a fundamental mistake during development.
Now I will describe an example.
main.js
import App from './app.js';
window.App = App;
import {increment} from './counter.js';
import {subIncrement} from './sub-counter.js';
export default class App {
increment() {
increment();
}
subIncrement() {
subIncrement();
}
}
let i=0;
export function increment() {
i++;
console.log(i);
}
import {increment} from './counter.js';
export function subIncrement() {
increment();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Новости</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<body>
<script>
function loadApplication() {
let app1 = new App;
app1.increment();
app1.increment();
app1.subIncrement();
let app2 = new App;
app2.increment();
app2.increment();
app2.subIncrement();
}
</script>
<script
src="./js/main.js"
onload="loadApplication();"
></script>
</body>
</html>
1
2
3
4
5
6
Answer the question
In order to leave comments, you need to log in
Because you work directly with only one file - counter.js
. If you want a new context every time - make a mini-factory (higher-order function):
function createCounter() {
let counter = 0;
function increment() {
counter++;
console.log(counter);
}
function decrement() {
counter--;
console.log(counter);
}
return {
get value() {
return counter;
},
increment,
decrement
};
}
class App {
constructor() {
this.counter = createCounter();
this.subCounter = createCounter();
}
increment() {
this.counter.increment();
}
subIncrement() {
this.subCounter.increment();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question