I'm new to ES6, still working/looking into it, I want to update my KUTE.js library to latest and greatest JavaScript standards.
I can basically create more functions, import them separately in index.js
and index-lite.js
but I wish I could make use of extend
to have a more consistent and abstract code, plus I don't want to have twice of the same code.
A very simple example looks like this:
// main.js
export const tweens = []
// STANDARD FUNCTIONS
export function Tween(el,start,end,ops){
this.el = el
this.start = start
this.end = end
return {this.el,this.start,this.end,this.ops}
}
Tween.prototype = {
start : function(){
tweens.push(this)
}
}
export function Render(tw){
tw.el.style.width = `${tw.start + tw.end}px`
}
export function Update(){
tweens.forEach(function(tw){
Render(tw)
})
}
// index-mini.js
import {Tween,Render,Update} from 'main.js'
// EXTENDED FUNCTIONS
export function TweenExtended(el,start,end,ops,extendingArgument){
this.el = el
this.start = start
this.end = end
// other stuff before returning the object
this.extendingProperty = `${extendingArgument} Hello there!`;
doSomeAction();
return {this.el,this.start,this.end,this.ops}
}
TweenExtended.prototype = {
start : function(){
tweens.push(this)
},
stop : function(){
const i = tweens.indexOf(this)
if (i !== -1) { tweens.splice(i, 1)
}
}
export function RenderExtended(tw,ops){
const widthValue = `${tw.start + tw.end}px`
tw.el.style.width = widthValue
// take an extended action
ops.update ? tw.el.innerHTML = widthValue
}
export function UpdateExtended(ops){
tweens.forEach(function(tw){
RenderExtended(tw,ops)
})
}
// index.js
import {TweenExtended,RenderExtended,UpdateExtended} from 'main.js'
Now, looking at Bergi's answer I just can't figure out a way to write a valid version of the following
// main.js
// EXTENDED FUNCTIONS
export function TweenExtended extends Tween(el,start,end,ops,extendingArgument){
// do what Tween does
// do other other stuff before returning the object
this.extendingProperty = `${extendingArgument} Hello there!`;
doSomeAction();
return {this.el,this.start,this.end,this.ops}
}
TweenExtended.prototype = {
// only add the additional methods
stop : function(){
const i = tweens.indexOf(this)
if (i !== -1) { tweens.splice(i, 1)
}
}
export function RenderExtended extends Render(tw,ops){
// do what parent functions does
// now do the extended actions
const widthValue = `${tw.start + tw.end}px`
ops.update ? tw.el.innerHTML = widthValue
}
export function UpdateExtended extends Update(ops){
// this probably needs to be rewritwen entirelly
tweens.forEach(function(tw){
RenderExtended(tw,ops)
})
}
// index.js
import {TweenExtended,RenderExtended,UpdateExtended} from 'main.js'
Questions:
export function AExtended extends A
, what is the correct syntax?- is it possible that the extended functions "merge" with their parent functions?
- if I were to use classes, is it possible to do the "merger"?
- if any of the above, can you please share some tip/sample/example?