I have been using the latest version of Vue.js and I really like the composition API but as I can't use vue for all my projects I have been experimenting with getting a similar syntax with native JS.
I have found that I can emulate es6 classes with the following code with the advantage of a syntax closer to Vue, no need to prefix all my variables with this
.
function Component (node) {
const test1 = "I am a private variable"
this.test2 = "I am a public variable"
getProps = () => {
return test1; // I am a private method with access to component variables
}
onTimeout = (callback) => {
setTimeout(callback, 1000);
}
};
function Media (node) {
Component.call(this, node); // copies public variables and methods
const sup = Object.assign({}, this); // acts like super in es6 classes
const props = getProps();
console.log(sup)
console.log(props)
onTimeout(() => {
console.log("I am executed on timeout")
})
}
new Media();
While it all seems to be functional and the browser doesn't throw any errors, typescript does not like the getProps
or extend
methods and throws the error Cannot find name 'getProps'
, when trying this code on codesandbox.io it also throws an error getProps is not defined
.
If you run this code snippet here on stackoverflow it should also work.
While I could prepend this.
to the methods that would make them public and no long private.
So my questions are:
- is this valid code?
- what exactly is going on here, if it is not valid why does this work in the browser?
- would there be any problem in using this in a production environnement?
- if so is there any other way I could accomplish the same thing?
- if not how do I tell typescript to not generate an error for the 2 methods?