JavaScript OOP dynamic getter setter - What am I doing wrong - javascript

I have been trying all day to find a way to make this work. It's really bugging me. I've read loads of articles on OOP and although i know my code is not perfect, I can't seem to get around the initial problem that I have outlined in my code below.
All of the code works except the dynamic getter/setter - If you read my comments in the code or run the code you can easily see why.
I have a feeling what I'm trying to do can't be done. Can someone tell me where I'm going wrong, or if It can't be done the way i have proposed.
var ext = {
db: {
string: function(def){
def=def || {};
def.type = "string";
return def;
},
autoId: function(def){
def=def || {};
def.defaultvalue = function(){
return Math.uuid(def.length, def.radix)
return def;
}
}
},
}
/*
* #ext.base: base class I can build out with common methods
*
*/
ext.base = function(){
/*
* place holder for the raw object data -
*
* {a:"martin webb",b:"is struggling with this"
*
*/
this._rawdata={}; // this can later be strigified for storage;
};
ext.base.prototype ={
init:function(o){
// pass in rawdata;
this.load(o);
},
put:function(){
//code removed
},
load: function(rawdata){
this._rawdata=rawdata || {};
}
}
/*
* #ext.kind: builds a new object we can use to make entities from our kind
* martin=new people();
*
*/
ext.db.kind=function(o){
this._kind=function(o){this.init(o);} //this will pass any passed in object in the base class at init;
this._kind.prototype = ext.base.prototype;
var self=this;
var prop,i=97; //ascii for "a";
for (prop in o){
if (o.hasOwnProperty(prop)) {
/*
* This is like a dynamic getter setter, we are adding it to the prototype;
*
* if you run the code when the function below is called
* value="martin webb" I need the var i to equal 97, and prop to = "name"
* in the function. I need a way to pass in and conserver these dynamic values
*/
this._kind.prototype[prop] =
function(value){
if (value) {
self.rawdata[i] = value; //ERROR i=99!
}
return self.rawdata[i] ; //get the correct data using the key
};
i++;
}
}
return this._kind; // return our new object so we can use it like var martin=new people();
}
debugger;
//lets make a new kind;
var people={};
people.name=ext.db.string();
people.info=ext.db.string();
people = new ext.db.kind(people);
//and now make some entities usinhg it;
var martin=new people();
//THE CODE WILL GO WRONG HERE, THE SETTER WILL NOT WORK (SEE ABOVE)
martin.name("martin webb")
martin.info("is struggling with this code")
var mike = new people({
a: "mike",
b: "has the solution"
});
console.log(mike.name()) //--> mike

I have found the solution. The answer was to use an enclosure and trap the loop index (i).
This was beautifully explained in the article by
Explaining javascript Scope and closures
The alteration to my code is as follows and works a treat!
var prop, i = 97; //ascii for "a";
//loop each property and make our own get/setter that works
//off our underlying compressed rawdata;
for (prop in o) {
if (o.hasOwnProperty(prop)) {
/*
* this is the trick
* use an enclosure and pass our loop index in the bottom
* with a self calling function, this locks the value of i;
*/
this._kind.prototype[prop] = function(k){
return function(value){
var key=String.fromCharCode(k);
//if we have a value passed in set it!
if (value){
this._rawdata[key]=value;
}
//always return our value;
return this._rawdata[key];
};
}(i); //here we call our function and lock index i;
i++;
}//end loop;

Related

How to write code to check if the value of a variable has changed in real time (JavaScript) [duplicate]

Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.
This question was originally posted in 2009 and most of the existing answers are either outdated, ineffective, or require the inclusion of large bloated libraries:
Object.watch and Object.observe are both deprecated and should not be used.
onPropertyChange is a DOM element event handler that only works in some versions of IE.
Object.defineProperty allows you to make an object property immutable, which would allow you to detect attempted changes, but it would also block any changes.
Defining setters and getters works, but it requires a lot of setup code and it does not work well when you need to delete or create new properties.
As of 2018, you can now use the Proxy object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
var targetObj = {};
var targetProxy = new Proxy(targetObj, {
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
return true;
}
});
targetProxy.hello_world = "test"; // console: 'hello_world set to test'
The only drawbacks of the Proxy object are:
The Proxy object is not available in older browsers (such as IE11) and the polyfill cannot fully replicate Proxy functionality.
Proxy objects do not always behave as expected with special objects (e.g., Date) -- the Proxy object is best paired with plain Objects or Arrays.
If you need to observe changes made to a nested object, then you need to use a specialized library such as Observable Slim (which I have published). It works like this:
var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
console.log(JSON.stringify(changes));
});
p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
Yes, this is now completely possible!
I know this is an old thread but now this effect is possible using accessors (getters and setters): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters
You can define an object like this, in which aInternal represents the field a:
x = {
aInternal: 10,
aListener: function(val) {},
set a(val) {
this.aInternal = val;
this.aListener(val);
},
get a() {
return this.aInternal;
},
registerListener: function(listener) {
this.aListener = listener;
}
}
Then you can register a listener using the following:
x.registerListener(function(val) {
alert("Someone changed the value of x.a to " + val);
});
So whenever anything changes the value of x.a, the listener function will be fired. Running the following line will bring the alert popup:
x.a = 42;
See an example here: https://jsfiddle.net/5o1wf1bn/1/
You can also user an array of listeners instead of a single listener slot, but I wanted to give you the simplest possible example.
Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
// Console
function print(t) {
var c = document.getElementById('console');
c.innerHTML = c.innerHTML + '<br />' + t;
}
// Demo
var myVar = 123;
Object.defineProperty(this, 'varWatch', {
get: function () { return myVar; },
set: function (v) {
myVar = v;
print('Value changed! New value: ' + v);
}
});
print(varWatch);
varWatch = 456;
print(varWatch);
<pre id="console">
</pre>
Other example
// Console
function print(t) {
var c = document.getElementById('console');
c.innerHTML = c.innerHTML + '<br />' + t;
}
// Demo
var varw = (function (context) {
/**
* Declare a new variable.
*
* #param {string} Variable name.
* #param {any | undefined} varValue Default/Initial value.
* You can use an object reference for example.
*/
return function (varName, varValue) {
var value = varValue;
Object.defineProperty(context, varName, {
get: function () { return value; },
set: function (v) {
value = v;
print('Value changed! New value: ' + value);
}
});
};
})(window);
varw('varWatch'); // Declare without initial value
print(varWatch);
varWatch = 456;
print(varWatch);
print('---');
varw('otherVarWatch', 123); // Declare with initial value
print(otherVarWatch);
otherVarWatch = 789;
print(otherVarWatch);
<pre id="console">
</pre>
No.
But, if it's really that important, you have 2 options (first is tested, second isn't):
First, use setters and getters, like so:
var myobj = {a : 1};
function create_gets_sets(obj) { // make this a framework/global function
var proxy = {}
for ( var i in obj ) {
if (obj.hasOwnProperty(i)) {
var k = i;
proxy["set_"+i] = function (val) { this[k] = val; };
proxy["get_"+i] = function () { return this[k]; };
}
}
for (var i in proxy) {
if (proxy.hasOwnProperty(i)) {
obj[i] = proxy[i];
}
}
}
create_gets_sets(myobj);
then you can do something like:
function listen_to(obj, prop, handler) {
var current_setter = obj["set_" + prop];
var old_val = obj["get_" + prop]();
obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));
}
then set the listener like:
listen_to(myobj, "a", function(oldval, newval) {
alert("old : " + oldval + " new : " + newval);
}
Second, you could put a watch on the value:
Given myobj above, with 'a' on it:
function watch(obj, prop, handler) { // make this a framework/global function
var currval = obj[prop];
function callback() {
if (obj[prop] != currval) {
var temp = currval;
currval = obj[prop];
handler(temp, currval);
}
}
return callback;
}
var myhandler = function (oldval, newval) {
//do something
};
var intervalH = setInterval(watch(myobj, "a", myhandler), 100);
myobj.set_a(2);
Sorry to bring up an old thread, but here is a little manual for those who (like me!) don't see how Eli Grey's example works:
var test = new Object();
test.watch("elem", function(prop,oldval,newval){
//Your code
return newval;
});
Hope this can help someone
As Luke Schafer's answer (note: this refers to his original post; but the whole point here remains valid after the edit), I would also suggest a pair of Get/Set methods to access your value.
However I would suggest some modifications (and that's why I'm posting...).
A problem with that code is that the field a of the object myobj is directly accessible, so it's possible to access it / change its value without triggering the listeners:
var myobj = { a : 5, get_a : function() { return this.a;}, set_a : function(val) { this.a = val; }}
/* add listeners ... */
myobj.a = 10; // no listeners called!
Encapsulation
So, to guarantee that the listeners are actually called, we would have to prohibit that direct access to the field a. How to do so? Use a closure!
var myobj = (function() { // Anonymous function to create scope.
var a = 5; // 'a' is local to this function
// and cannot be directly accessed from outside
// this anonymous function's scope
return {
get_a : function() { return a; }, // These functions are closures:
set_a : function(val) { a = val; } // they keep reference to
// something ('a') that was on scope
// where they were defined
};
})();
Now you can use the same method to create and add the listeners as Luke proposed, but you can rest assured that there's no possible way to read from or write to a going unnoticed!
Adding encapsulated fields programmatically
Still on Luke's track, I propose now a simple way to add encapsulated fields and the respective getters/setters to objects by the means of a simple function call.
Note that this will only work properly with value types. For this to work with reference types, some kind of deep copy would have to be implemented (see this one, for instance).
function addProperty(obj, name, initial) {
var field = initial;
obj["get_" + name] = function() { return field; }
obj["set_" + name] = function(val) { field = val; }
}
This works the same as before: we create a local variable on a function, and then we create a closure.
How to use it? Simple:
var myobj = {};
addProperty(myobj, "total", 0);
window.alert(myobj.get_total() == 0);
myobj.set_total(10);
window.alert(myobj.get_total() == 10);
Recently found myself with the same issue. Wanted to listen for on change of a variable and do some stuff when the variable changed.
Someone suggested a simple solution of setting the value using a setter.
Declaring a simple object that keeps the value of my variable here:
var variableObject = {
value: false,
set: function (value) {
this.value = value;
this.getOnChange();
}
}
The object contains a set method via which I can change the value. But it also calls a getOnChange() method in there. Will define it now.
variableObject.getOnChange = function() {
if(this.value) {
// do some stuff
}
}
Now whenever I do variableObject.set(true), the getOnChange method fires, and if the value was set as desired (in my case: true), the if block also executes.
This is the simplest way I found to do this stuff.
If you're using jQuery {UI} (which everyone should be using :-) ), you can use .change() with a hidden <input/> element.
AngularJS (I know this is not JQuery, but that might help. [Pure JS is good in theory only]):
$scope.$watch('data', function(newValue) { ..
where "data" is name of your variable in the scope.
There is a link to doc.
For those tuning in a couple years later:
A solution for most browsers (and IE6+) is available that uses the onpropertychange event and the newer spec defineProperty. The slight catch is that you'll need to make your variable a dom object.
Full details:
http://johndyer.name/native-browser-get-set-properties-in-javascript/
Easiest way I have found, starting from this answer:
// variable holding your data
const state = {
count: null,
update() {
console.log(`this gets called and your value is ${this.pageNumber}`);
},
get pageNumber() {
return this.count;
},
set pageNumber(pageNumber) {
this.count = pageNumber;
// here you call the code you need
this.update(this.count);
}
};
And then:
state.pageNumber = 0;
// watch the console
state.pageNumber = 15;
// watch the console
The functionality you're looking for can be achieved through the use of the "defineProperty()" method--which is only available to modern browsers:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
I've written a jQuery extension that has some similar functionality if you need more cross browser support:
https://github.com/jarederaj/jQueue
A small jQuery extension that handles queuing callbacks to the
existence of a variable, object, or key. You can assign any number of
callbacks to any number of data points that might be affected by
processes running in the background. jQueue listens and waits for
these data you specify to come into existence and then fires off the
correct callback with its arguments.
Not directly: you need a pair getter/setter with an "addListener/removeListener" interface of some sort... or an NPAPI plugin (but that's another story altogether).
A rather simple and simplistic solution is to just use a function call to set the value of the global variable, and never set its value directly. This way you have total control:
var globalVar;
function setGlobalVar(value) {
globalVar = value;
console.log("Value of globalVar set to: " + globalVar);
//Whatever else
}
There is no way to enforce this, it just requires programming discipline... though you can use grep (or something similar) to check that nowhere does your code directly set the value of globalVar.
Or you could encapsulate it in an object and user getter and setter methods... just a thought.
With the help of getter and setter, you can define a JavaScript class that does such a thing.
First, we define our class called MonitoredVariable:
class MonitoredVariable {
constructor(initialValue) {
this._innerValue = initialValue;
this.beforeSet = (newValue, oldValue) => {};
this.beforeChange = (newValue, oldValue) => {};
this.afterChange = (newValue, oldValue) => {};
this.afterSet = (newValue, oldValue) => {};
}
set val(newValue) {
const oldValue = this._innerValue;
// newValue, oldValue may be the same
this.beforeSet(newValue, oldValue);
if (oldValue !== newValue) {
this.beforeChange(newValue, oldValue);
this._innerValue = newValue;
this.afterChange(newValue, oldValue);
}
// newValue, oldValue may be the same
this.afterSet(newValue, oldValue);
}
get val() {
return this._innerValue;
}
}
Assume that we want to listen for money changes, let's create an instance of MonitoredVariable with initial money 0:
const money = new MonitoredVariable(0);
Then we could get or set its value using money.val:
console.log(money.val); // Get its value
money.val = 2; // Set its value
Since we have not defined any listeners for it, nothing special happens after money.val changes to 2.
Now let's define some listeners. We have four listeners available: beforeSet, beforeChange, afterChange, afterSet.
The following will happen sequentially when you use money.val = newValue to change variable's value:
money.beforeSet(newValue, oldValue);
money.beforeChange(newValue, oldValue); (Will be skipped if its value not changed)
money.val = newValue;
money.afterChange(newValue, oldValue); (Will be skipped if its value not changed)
money.afterSet(newValue, oldValue);
Now we define afterChange listener which be triggered only after money.val has changed (while afterSet will be triggered even if the new value is the same as the old one):
money.afterChange = (newValue, oldValue) => {
console.log(`Money has been changed from ${oldValue} to ${newValue}`);
};
Now set a new value 3 and see what happens:
money.val = 3;
You will see the following in the console:
Money has been changed from 2 to 3
For full code, see https://gist.github.com/yusanshi/65745acd23c8587236c50e54f25731ab.
In my case, I was trying to find out if any library I was including in my project was redefining my window.player. So, at the begining of my code, I just did:
Object.defineProperty(window, 'player', {
get: () => this._player,
set: v => {
console.log('window.player has been redefined!');
this._player = v;
}
});
Based On akira's answer I added that you can manipulate the dom through the listerner.
https://jsfiddle.net/2zcr0Lnh/2/
javascript:
x = {
aInternal: 10,
aListener: function(val) {},
set a(val) {
this.aInternal = val;
this.aListener(val);
},
get a() {
return this.aInternal;
},
registerListener: function(listener) {
this.aListener = listener;
}
}
x.registerListener(function(val) {
document.getElementById('showNumber').innerHTML = val;
});
x.a = 50;
function onClick(){
x.a = x.a + 1;
}
html:
<div id="showNumber">
</div>
<button onclick="onClick()">
click me to rerender
</button>
The registerListener method is fired when the variable x.a changes.
//ex:
/*
var x1 = {currentStatus:undefined};
your need is x1.currentStatus value is change trigger event ?
below the code is use try it.
*/
function statusChange(){
console.log("x1.currentStatus_value_is_changed"+x1.eventCurrentStatus);
};
var x1 = {
eventCurrentStatus:undefined,
get currentStatus(){
return this.eventCurrentStatus;
},
set currentStatus(val){
this.eventCurrentStatus=val;
//your function();
}
};
or
/* var x1 = {
eventCurrentStatus:undefined,
currentStatus : {
get : function(){
return Events.eventCurrentStatus
},
set : function(status){
Events.eventCurrentStatus=status;
},
}*/
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="create"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="edit"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
console.log("currentStatus = "+ x1.currentStatus);
or
/* global variable ku*/
var jsVarEvents={};
Object.defineProperty(window, "globalvar1", {//no i18n
get: function() { return window.jsVarEvents.globalvarTemp},
set: function(value) { window.window.jsVarEvents.globalvarTemp = value; }
});
console.log(globalvar1);
globalvar1=1;
console.log(globalvar1);
Please guys remember the initial question was for VARIABLES, not for OBJECTS ;)
in addition to all answers above, I created a tiny lib called forTheWatch.js,
that use the same way to catch and callback for changes in normal global variables in javascript.
Compatible with JQUERY variables, no need to use OBJECTS, and you can pass directly an ARRAY of several variables if needed.
If it can be helpful... :
https://bitbucket.org/esabora/forthewatch Basically you just have to call the function :
watchIt("theVariableToWatch", "varChangedFunctionCallback");
And sorry by advance if not relevant.
The question is about variables, not object properties! So my approach is to take advantage of the window object, with its custom getters/setters, and then use/change the variable like a "normal" variable (not like an object property).
The simplest way is that of #José Antonio Postigo in his answer (i voted that answer). What I'd like to do here, is to reduce that to an even simpler "creator" function (so even someone that does not understand object getters/setters can easily use it).
A live example is here: https://codepen.io/dimvai/pen/LYzzbpz
This is the general "creator" function you must have as is:
let createWatchedVariable = (variableName,initialValue,callbackFunction) => {
// set default callback=console.log if missing
callbackFunction ??= function(){console.log(variableName+" changed to " + window[variableName])};
// the actual useful code:
Object.defineProperty(window, variableName, {
set: function(value) {window["_"+variableName] = value; callbackFunction()},
get: function() {return window["_"+variableName]}
});
window[variableName]=initialValue??null;
};
Then, instead of declaring the variable using var or let, use this:
// 1st approach - default callback//
createWatchedVariable ('myFirstVariable',12);
// instead of: let myFirstVariable = 12;
Or, in order to use your custom callback (instead of the default console.log) use:
// 2nd approach - set a custom callback//
var myCallback = ()=>{/*your custom code...*/}
// now use callback function as the third optional argument
createWatchedVariable('mySecondVariable',0,myCallback);
That's it! Now, you can change it like a "normal" variable:
myFirstVariable = 15; // logs to console
myFirstVariable++; // logs to console
mySecondVariable = 1001; // executes your custom code
mySecondVariable++; // executes your custom code
The solution of #akira and #mo-d-genesis can be further simplified because the DOM manipulation does not depend on state in this example:
CodePen
const render = (val) => {
document.getElementById("numberDiv").innerHTML = val;
};
state = {
_value_internal: undefined,
set value(val) {
// 1. set state value
this._value_internal = val;
// 2. render user interface
render(val);
},
get value() {
return this._value_internal;
},
};
const onClick = () => {
state.value = state.value + 1; // state change leads to re-render!
};
// set default value
state.value = 0;
The corresponding html:
<div id="numberDiv"></div>
<button onclick="onClick()">
Click to rerender
</button>
Remarks:
I renamed variables and functions to better reflect their semantics.
FYI: Svelte offers a very similar reactive behavior by changing variables
It's not directly possible.
However, this can be done using CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
The below method accepts an array of variable names as an input and adds event listener for each variable and triggers the event for any changes to the value of the variables.
The Method uses polling to detect the change in the value. You can increase the value for timeout in milliseconds.
function watchVariable(varsToWatch) {
let timeout = 1000;
let localCopyForVars = {};
let pollForChange = function () {
for (let varToWatch of varsToWatch) {
if (localCopyForVars[varToWatch] !== window[varToWatch]) {
let event = new CustomEvent('onVar_' + varToWatch + 'Change', {
detail: {
name: varToWatch,
oldValue: localCopyForVars[varToWatch],
newValue: window[varToWatch]
}
});
document.dispatchEvent(event);
localCopyForVars[varToWatch] = window[varToWatch];
}
}
setTimeout(pollForChange, timeout);
};
let respondToNewValue = function (varData) {
console.log("The value of the variable " + varData.name + " has been Changed from " + varData.oldValue + " to " + varData.newValue + "!!!");
}
for (let varToWatch of varsToWatch) {
localCopyForVars[varToWatch] = window[varToWatch];
document.addEventListener('onVar_' + varToWatch + 'Change', function (e) {
respondToNewValue(e.detail);
});
}
setTimeout(pollForChange, timeout);
}
By calling the Method:
watchVariables(['username', 'userid']);
It will detect the changes to variables username and userid.
This is what I did: Call JSON.stringify twice and compare the two strings...
Drawbacks:
You can only know whether the whole object changes
You have to detect changes manually
You better have only primitive fields in the object(no properties, no functions...)
This is NOT a production ideal answer, but what it is doing is setting an interval in JavaScript for every 100 milliseconds and checking to see if the variable is changed and when it is, it does something (anything intended by the OP) and then clears the interval, so it sort of simulates what the OP is asking.
let myvar = "myvar";
const checkChange = setInterval(() => {
if (myvar !== "myvar") {
console.log("My precious var has been changed!");
clearInterval(checkChange);
}
}, 100);
Now if myvar gets changed to something else then this program will say "My precious var has been changed!" :)
This is an old great question, has more than 12 years. Also, there are many ways to solve it. However, most of then are complicated or using old JS concepts we are in 2022 and we can use ES6 to improve our code.
I will implemented two main solutions that I constantly use.
Simple variable
If we have a simple variable and we don't care about reutilization then we can declare our variable as an object. We define a set and get methods and a listener attribute to handle the "change" event.
const $countBtn = document.getElementById('counter')
const $output = document.getElementById('output')
const counter = {
v: 0,
listener: undefined,
set value(v) {
this.v = v
if (this.listener) this.listener(v)
},
get value() { return this.v },
count() { this.value++ },
registerListener(callback) {
this.listener = callback
},
}
const countOnClick = () => { counter.count() }
$countBtn.onclick = countOnClick
counter.registerListener(v => {
$output.textContent = v
})
counter.value = 50
#output {
display: block;
font-size: 2em;
margin-top: 0.67em;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
<button id="counter">Count</button>
<div id="output"></div>
Advanced Class for reusability
If we will have multiple variables and we need to monitor them, we can create a class and then apply it to our variables. I recommend to add two listeners one beforeChange and afterChange this will give you flexibility to use the variable in different process.
class ObservableObject {
constructor(v) {
this.v = v ?? 0
this.on = {
beforeChange(newValue, oldValue) {},
afterChange(newValue, oldValue) {},
}
}
set value(newValue) {
const oldValue = this.v
// newValue, oldValue are the same
if (oldValue === newValue) return
this.on.beforeChange(newValue, oldValue)
this.v = newValue
this.on.afterChange(newValue, oldValue)
}
get value() { return this.v }
}
const $countABtn = document.getElementById('counter-a')
const $countBBtn = document.getElementById('counter-b')
const $outputA = document.getElementById('output-a')
const $outputB = document.getElementById('output-b')
const counterA = new ObservableObject()
const counterB = new ObservableObject()
const countOnClick = counter => { counter.value++ }
const onChange = (v, output) => { output.textContent = v }
$countABtn.onclick = () => { countOnClick(counterA) }
$countBBtn.onclick = () => { countOnClick(counterB) }
counterA.on.afterChange = v => { onChange(v, $outputA) }
counterB.on.afterChange = v => { onChange(v, $outputB) }
counterA.value = 50
counterB.value = 20
.wrapper {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-items: center;
width: 100vw
}
.item {
width: 50%
}
.output {
display: block;
font-size: 2em;
margin-top: 0.67em;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
<div class="wrapper">
<div class="item">
<button id="counter-a">Count A</button>
<div id="output-a" class="output"></div>
</div>
<div class="item">
<button id="counter-b">Count B</button>
<div id="output-b" class="output"></div>
</div>
</div>
This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using #Output and event emitters. Going off of the example in custom listener answer:
ChildComponent.html
<button (click)="increment(1)">Increment</button>
ChildComponent.ts
import {EventEmitter, Output } from '#angular/core';
#Output() myEmitter: EventEmitter<number> = new EventEmitter<number>();
private myValue: number = 0;
public increment(n: number){
this.myValue += n;
// Send a change event to the emitter
this.myEmitter.emit(this.myValue);
}
ParentComponent.html
<child-component (myEmitter)="monitorChanges($event)"></child-component>
<br/>
<label>{{n}}</label>
ParentComponent.ts
public n: number = 0;
public monitorChanges(n: number){
this.n = n;
console.log(n);
}
This will now update non parent each time the child button is clicked. Working stackblitz
I came here looking for same answer for node js. So here it is
const events = require('events');
const eventEmitter = new events.EventEmitter();
// Createing state to watch and trigger on change
let x = 10 // x is being watched for changes in do while loops below
do {
eventEmitter.emit('back to normal');
}
while (x !== 10);
do {
eventEmitter.emit('something changed');
}
while (x === 10);
What I am doing is setting some event emitters when values are changed and using do while loops to detect it.
I searched for JavaScript two-way data binding library and came across this one.
I did not succeed to make it work in DOM to variable direction, but in variable to DOM direction it works and that is what we need here.
I have rewritten it slightly, as the original code is very hard to read (for me). It uses
Object.defineProperty, so the second most upvoted answer by Eliot B. at least partially wrong.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
const dataBind = (function () {
const getElementValue = function (selector) {
let element = document.querySelectorAll(selector)[0];
return 'value' in element ? element.value : element.innerHTML;
};
const setElementValue = function (selector, newValue) {
let elementArray = document.querySelectorAll(selector);
for (let i = 0; i < elementArray.length; i++) {
let element = elementArray[i];
if ('value' in element) {
element.value = newValue;
if (element.tagName.toLowerCase() === 'select'){
let options = element.querySelectorAll('option');
for (let option in options){
if (option.value === newValue){
option.selected = true;
break;
}
}
}
} else {
element.innerHTML = newValue;
}
}
};
const bindModelToView = function (selector, object, property, enumerable) {
Object.defineProperty(object, property, {
get: function () {
return getElementValue(selector);
},
set: function (newValue) {
setElementValue(selector, newValue);
},
configurable: true,
enumerable: (enumerable)
});
};
return {
bindModelToView
};
})();
</script>
</head>
<body>
<div style="padding: 20%;">
<input type="text" id="text" style="width: 40px;"/>
</div>
<script>
let x = {a: 1, b: 2};
dataBind.bindModelToView('#text', x, 'a'); //data to dom
setInterval(function () {
x.a++;
}, 1000);
</script>
</body>
</html>
JSFiddle.
JSFiddle with original code.
In the provided example a property of object x updated by the setInterval and value of text input automatically updated as well. If it is not enough and event is what you looking for, you can add onchange listener to the above input. Input also can be made hidden if needed.
Utils = {
eventRegister_globalVariable : function(variableName,handlers){
eventRegister_JsonVariable(this,variableName,handlers);
},
eventRegister_jsonVariable : function(jsonObj,variableName,handlers){
if(jsonObj.eventRegisteredVariable === undefined) {
jsonObj.eventRegisteredVariable={};//this Object is used for trigger event in javascript variable value changes ku
}
Object.defineProperty(jsonObj, variableName , {
get: function() {
return jsonObj.eventRegisteredVariable[variableName] },
set: function(value) {
jsonObj.eventRegisteredVariable[variableName] = value; handlers(jsonObj.eventRegisteredVariable[variableName]);}
});
}

Passing Object's Instance in Javascript

Here is what I'm trying to do. I'm trying to pass an instance of order to bill, where it would be indexed. The thing is that it's not working.
Am I stretching JS too thin here?
Any example on how to do this, or some reading material?
EDIT: Maybe I should add that this is supposed to be the user interface for a POS (Point of Sale) system. It should accept the order of products (each one with variable quantity), and process in the client's side the subtotal, total and number of items in the bill.
EDIT2: Not native english speaker. Maybe the names that I choose did not best suited the problem.
function Bill (prefix,maxForms,minForms) {
this.prefix = prefix;
this.maxForms = maxForms;
this.minForms = minForms;
this.items = [];
this.total = 0;
this.addOrder = function(order) {
if (this.items.length == 0)
{
this.items.push(order);
}
for (i=0;i<this.items.length;i++){
if (this.items[i].name === order.name) {
this.items[i].quantity = order.quantity;
this.items[i].price = order.price;
}
else {
this.items.push(order);
}
this.total = this.total + order.getSubTotal();
}
}
}
function Order (name,price,quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.getSubtotal = function () {
return this.price*this.quantity;
}
this.changeQuantity = function (newQuantity) {
this.quantity = newQuantity;
}
this.incrementQuantity = function () {
this.quantity = this.quantity + 1;
}
}
Here's an issue:
for (i = 0;/*...*/)
I would suggest you spend a little more time in JS.
It does look a lot like C / Java / C# / PHP, etc...
The problem, however, is that JS does not have any notion of block scope*.
* until ES6, that is
It only deals with function scope.
That is, a variable has the same reference through the whole function where it's defined (via var).
If a variable is not defined via var, the function goes up to its parent to find the value of the variable, and up from there, and up from there, until it hits window.<varname>.
You might actually be modifying window.i in your class' instance.
function Bill ( ) {
var bill = this,
i = 0;
for (i=0; /* ... */) { /*...*/ }
}
That said, you might do to spend time getting to know JS.
Most of what you've written looks absolutely fine, in English, as well.
I might break it down a little further:
function Bill () {
var bill = this;
extend(bill, {
total : 0,
items : [],
addOrder : function (order) {
var match = bill.findOrder(order.name);
if (!match) { bill.items.push(order); }
else { bill.updateOrder(match, order); }
bill.updateTotal();
},
findOrder : function (name) {
var matches = bill.items.filter(function (order) {
return order.name === name;
});
return matches[0];
},
updateOrder : function (current, updated) {
/* I don't know if you want to replace the old order, or add to it... */
/* so I'm "replacing" it, instead of increasing quantity, like you did */
current.quantity = updated.quantity;
current.price = updated.price;
},
updateTotal : function () {
bill.total = bill.items
.map(function (order) { return order.getSubtotal(); })
.reduce(function (tally, price) { return tally + price; }, 0);
}
});
}
var bill = new Bill();
bill.addOrder(new Order(/*...*/));
I'm doing a few things differently, here.
First, extend isn't a "built-in" function; there are a lot of implementations, in all sorts of libraries, but basically, it just saves me from writing bill.x = x; bill.y = y; bill.z = z;..., and use an object, instead.
Next, I'm using var bill = this;
and bill.method = function () { bill.total = /*...*/; };
instead of this.method = function () { };, because once you go two levels down, in functions, this no longer means the object you think it does.
this.method = function () {
this.async(function (response) {
// unless you change it yourself, `this` probably means `window`
this.value = response; // oops
});
};
// instead, try
var thing = this;
thing.method = function () {
thing.async(function (response) {
thing.value = response;
});
};
Of course, you can always mix and match, as long as you know how far down you can go (one level)...
...but that means you really, really need to care about using this a whole lot.
var thing = this;
this.method = function () {
this.async(function (val) {
thing.value = val;
});
};
Much more confusing than just referring to the instance by a variable, rather than combining the two.
There are dozens of ways of doing this; some look very class-like, others might be 100% functional, and in ES6, you might just use classes altogether.
But there are some ideas, and some reasons behind doing them that way (especially if you don't know where the differences are in JS vs the other C-looking languages).
I don't think you're stretching JS too thin, at all.
Once all of the issues on line 80 are fixed. All you need to do is:
var order = new Order("My Order", 12, 2);
var bill = new Bill(blah, blah, blah);
bill.addOrder(order);
A few issues right off the bat:
this.total = this.total + order.subTotal();·
There is a garbage char at the end.
Order does not have a subtotal function. It should be getSubtotal.
The 2 assignments to this.items[i].quantity and this.items[i].price are superfluous, since you are assigning properties to themselves. Remember, this.items[i] === order. This is not a bug, but it is inefficient.
You should have something like this.total = 0; at the top of Bill.
I think you want:
this.items[i].quantity += order.quantity;
this.items[i].price += order.price;
This will update quantity with whatever quantity order has. Secondly, I see you have an order function. Not an order object. Was that intentional? Are you planning to add instances of this bill/order object to each other? I don't think that's where you were going. Make sure they are separate objects that you are nesting.
Are you getting anything except undefined? I don't think you are because you're not returning anything.
Put:
return this;
at the end of your functions. Make sure you save them to a var when you make them:
bill = Bill(v,v,v);
order = Order(v,v,v);
then you can:
bill.addOrder(order);
See if that helps.

Accessing the value of an observable inside a plain JS array in Knockout JS?

Background
I have a plain JS array, initially empty. I later populate it with values. The values sent to it are numbers that are Knockout observables. Later, I want to compare those values to values in another, knockout observable array. My problem is that whenever I pass the index of the current item in my array loop, and pass that index value (a number!), the array returns a function. To get an idea, look at the JS that follows.
Note that my project and actual script is viewable on JSBin. Further, to view the problem in the console, you have to add assignments, then press 'sort'.
JSBin: http://jsbin.com/fehoq/177/edit]1
JS
//example script that follows actual script
var _this = this;
//initialize my array
this. lowest = [];
// I want to compare values in lowest to values in this array
this.scores = ko.observableArray();
// method that does comparison
this.myMethod = function(){
// initialize my helper, k
var k;
...
// loop through one array
ko.utils.arrayForEach(_this.scores(), function (score) {
// make sure my value is a number...
if (!isNaN(parseFloat(score()))) {
// this is important, I need to current index for comparison
k = _this.scores.indexOf(score);
console.log(k);
// this is where things break - it prints a function, not a value!
console.log(_this.lowest[k]);
// useless check, the value is a function, so they're always different
if (score()!=_this.lowest[k]){
// do stuff
}
}
}
}
Update
Putting the method I'm using, maybe someone will notice something I missed given that my syntax is correct(?).
this.mean = (function(scores,i) {
var m = 0;
var count = 0;
var k;
ko.utils.arrayForEach(_this.scores(), function(score) {
console.log([typeof score(), score()]);
if (!isNaN(parseFloat(score()))) {
console.log(i);
console.log(_this.lowest[i]);
if (score() != _this.lowest[i]) {
m += parseFloat(score());
count += 1;
}
}
});
if (count) {
m = m / count;
return m.toFixed(2);
} else {
return 'N/A';
}
});
}
Update 2
Just in case someone else wanders over here since my problem isn't solve still. The following code is how I set the value of lowest:
this.dropLowestScores = function() {
ko.utils.arrayForEach(_this.students(), function(student){
var comparator = function(a,b){
if(a()<b()){
return 1;
} else if(a() > b()){
return -1;
} else {
return 0;
}
};
var tmp = student.scores().slice(0);
tmp.sort(comparator);
student.lowest = ko.observableArray(tmp.splice((tmp.length-2),tmp.length-1));
});
};
Outstanding Questions, 5/9/2014
Jeremy's script runs but without the desired effects. For example, console.log(_this.lowest[k]) prints undefined, just as mine does. Further, the matched scores aren't skipped, which they should be.
Jeremy's script specifies lowest as a ko.observable. My script also now has lowest as a ko.observable, but why shouldn't a plain JS array work for this? I only need lowest to update when the button it's bound to is clicked, and those bindings are already taken care of.
That is how observables work in Knockout.
When you create one, you are creating a function.
var myObservable1 = ko.observable(); // Create it.
var myObservable2 = ko.observable("Hola!"); // Create it with a value.
console.log(typeof myObservable2); // It is indeed a function
console.log(typeof myObservable2()); // That returns a string
console.log(myObservable2()); // And get the value.
EDIT BASED ON QUESTION IN COMMENTS
var koTest = ko.observableArray();
koTest.push("Line0");
koTest.push("Line1");
koTest.push("Line2");
koTest.push("Line3");
koTest.push("Line4");
var jsTest = [];
jsTest.push("Line0");
jsTest.push("Line1");
jsTest.push("Line2");
jsTest.push("Line3");
jsTest.push("Line4");
alert(koTest()[2]);
alert(jsTest[2]);
alert(koTest()[2] === jsTest[2]);
Test Code
I went ahead and make a runnable test of your code and everything was working just fine for me. I had to make some assumptions about the contents of _this -- in particular the declaration of lowest, which I made an observableArray based on how you were accessing it.
Anyways, this code runs:
var _this = {
scores: ko.observableArray(),
lowest: ko.observableArray()
};
var mean = (function(scores) {
var m = 0;
var count = 0;
var k;
ko.utils.arrayForEach(_this.scores(), function(score) {
console.log([typeof score(), score()]);
if (!isNaN(parseFloat(score()))) {
k = _this.scores.indexOf(score);
console.log(k);
console.log(_this.lowest[k]);
if (score() != _this.lowest[k]) {
m += parseFloat(score());
count += 1;
}
}
});
if (count) {
m = m / count;
return m.toFixed(2);
} else {
return 'N/A';
}
});
for (var i = 0; i < 10; i++) {
_this.scores.push(ko.observable(i));
}
var m = mean();
alert(m);

Needing some visitor-like design pattern

I will give you a sample example of my problem to remove the logical complexity and let you be focus on the important part. Of course, this example will be a bit useless...
I have a tree structure where node are like that
{
path: "...",
childs : []
}
Now, I have to write all the full paths from root to each leaf in an array.
My design is very poor:
function listPaths(node) {
var result = [];
function listForNode(n, parentFullPath) {
var thisPath = parentFullPath + "/" + n.path;
result.push(thisPath);
n.childs.forEach(function (child) {
listForNode(child, thisPath);
});
}
listForNode(node, "");
return result;
}
It could be nice but I can't write the test with Mocha without having an insane 600 line code test file. At this moment, you should be asking why. The reason is the complexity of the real purpose, that's not relevant for my question. My goal is to having something 'mockable' cause I'm used to. (Java dev). But I fail.
Do you have any pattern that I can use to resolve this one? I'm not really good at JS patterns. :/
Visitor? Making an Y Combinator? So many possibility...
Thank you for reading me
You need to remember that functions are first class citizens in javascript.
I see that essentially what you have is something like
function createVisitor(parentsAccumulatorInitialValue, parentsAccumulator){
var visitor = function myVisitor (node) {
var result;
function listForNode(n, parentsAcc) {
var thisPath = parentsAccumulator(parentsAcc, n);
result.push(thisPath);
n.childs && n.childs.forEach(function (child) {
listForNode(child, thisPath);
});
}
result = [];
listForNode(node, parentsAccumulatorInitialValue());
return result;
}
return visitor;
}
var listPaths = createVisitor(
function parentInit () {
return "";
},
function parentAcc (parentFullPath, n) {
return parentFullPath + "/" + n.path;
});
But that's not the only abstraction you could take care of:
function createVisitor2(
totalAccumulatorInitialValue,
totalAccumulator,
parentsAccumulatorInitialValue,
parentsAccumulator){
var visitor = function myVisitor (node) {
var total;
function listForNode(n, parentsAcc) {
var thisPath = parentsAccumulator(parentsAcc, n);
total = totalAccumulator(total, thisPath, n);
n.childs && n.childs.forEach(function (child) {
listForNode(child, thisPath);
});
}
total = totalAccumulatorInitialValue();
listForNode(node, parentsAccumulatorInitialValue());
return total;
}
return visitor;
}
var listPaths2 = createVisitor2(
function totalInit() {
return [];
},
function totalAcc(total, thisPath, n){
total.push(thisPath);
return total;
},
function parentInit () {
return "";
},
function parentAcc (parentFullPath, n) {
return parentFullPath + "/" + n.path;
});
Which might be pretty reasonable, but as you can see, I'm already beginning to have trouble finding appropriate names for these variables. In fact, I'd say the name of our function is bad, as doesn't create anything strictly like a visitor object I know of. However, it does work (BTW, I've slightly modified it to handle nulls as well as empty arrays):
> listPaths( { path:"foo",
childs: [{path:"bar", childs: null}, {path:"bob", childs: null}]})
["/foo", "/foo/bar", "/foo/bob"]
It can be modified even further so that your trees don't strictly even have the same structure... but we're already at 4 parameters, which isn't great. It'd be better if your visitor creator were passed a single extensible object with all the necessary methods or values. For instance, maybe (pseudocode):
function createVisitor3(opts) {
//assume we've defined GetDefaults() somewhere local to createVisitor3
// as well as assume that extend is defined somewhere that copies properties
// into a new object like various previously existing libraries do.
opts = extend({}, GetDefaults(), opts);
var totalAccumulatorInitialValue = opts.totalAccumulatorInitialValue;
var totalAccumulator = opts.totalAccumulator;
var parentsAccumulatorInitialValue = opts.parentsAccumulatorInitialValue;
var parentsAccumulator = opts.parentsAccumulator;
var childrenGetter = opts.childrenGetter;
/// etc.
...
}

Can you alter a Javascript function after declaring it?

Let's say I have var a = function() { return 1; }. Is it possible to alter a so that a() returns 2? Perhaps by editing a property of the a object, since every function is an object?
Update: Wow, thanks for all the responses. However, I'm afraid I wasn't looking to simply reassign a variable but actually edit an existing function. I am thinking along the lines of how you can combine partial functions in Scala to create a new PartialFunction. I am interested in writing something similar in Javascript and was thinking that the existing function could perhaps be updated, rather than creating an entirely new Function object.
You can do all kinds of fun stuff with javascript, including redefining functions:
let a = function() { return 1; }
console.log(a()); // 1
// keep a reference
let old = a;
// redefine
a = function() {
// call the original function with any arguments specified, storing the result
const originalResult = old.apply(old, arguments);
// add one
return originalResult + 1;
};
console.log(a()); // 2
Voila.
Edit: Updated to show this in a crazier scenario:
let test = new String("123");
console.log(test.toString()); // logs 123
console.log(test.substring(0)); // logs 123
String.prototype.substring = function(){ return "hahanope"; }
console.log(test.substring(0)); // logs hahanope
You can see here that even though "test" is defined first, and we redefine substring() afterwards, the change still applies.
Side note: you really should reconsider your architecture if you're doing this...you're going to confuse the crap out of some poor developer 5 years down the road when s/he's looking at a function definition that's supposed to return 1, but seems to always return 2....
So you want to modify the code of a function directly, in place, and not just reassign a different function to an existing variable.
I hate to say it, but as far as I have been able to figure it out - and I have tried -, it can't be done. True, a function is an object, and as such it has methods and properties which can be tweaked and overwritten on the object itself. Unfortunately, the function body is not one of them. It is not assigned to a public property.
The documentation on MDN lists the properties and methods of the function object. None of them gives us the opportunity to manipulate the function body from the outside.
That's because according to the spec, the function body is stored in the internal [[Code]] property of the function object, which can't be accessed directly.
I used something like this to modify an existing function whose declaration was not accessible to me:
// declare function foo
var foo = function (a) { alert(a); };
// modify function foo
foo = new Function (
"a",
foo.toSource()
.replace("alert(a)", "alert('function modified - ' + a)")
.replace(/^function[^{]+{/i,"") // remove everything up to and including the first curly bracket
.replace(/}[^}]*$/i, "") // remove last curly bracket and everything after<br>
);
Instead of toSource() you could probably use toString() to get a string containing the function's declaration. Some calls to replace() to prepare the string for use with the Function Constructor and to modify the function's source.
let a = function() { return 1; }
console.log(a()) // 1
a = function() { return 2; }
console.log(a()) // 2
technically, you're losing one function definition and replacing it with another.
How about this, without having to redefine the function:
var a = function() { return arguments.callee.value || 1; };
alert(a()); // => 1
a.value = 2;
alert(a()); // => 2
I am sticking to jvenema's solution, in which I don't like the global variable "old". It seems better to keep the old function inside of the new one:
function a() { return 1; }
// redefine
a = (function(){
var _a = a;
return function() {
// You may reuse the original function ...
// Typical case: Conditionally use old/new behaviour
var originalResult = _a.apply(this, arguments);
// ... and modify the logic in any way
return originalResult + 1;
}
})();
a() // --> gives 2
All feasible solutions stick to a "function wrapping approach".
The most reliable amongst them seems to be the one of rplantiko.
Such function wrapping easily can be abstracted away. The concept / pattern itself might be called "Method Modification". Its implementation definitely belongs to Function.prototype. It would be nice to be backed
one day by standard prototypal method modifiers like before, after, around, afterThrowing and afterFinally.
As for the aforementioned example by rplantiko ...
function a () { return 1; }
// redefine
a = (function () {
var _a = a;
return function () {
// You may reuse the original function ...
// Typical case: Conditionally use old/new behaviour
var originalResult = _a.apply(this, arguments);
// ... and modify the logic in any way
return originalResult + 1;
};
})();
console.log('a() ...', a()); // --> gives 2
.as-console-wrapper { min-height: 100%!important; top: 0; }
... and making use of around, the code would transform to ...
function a () { return 1; }
console.log('original a ...', a);
console.log('a() ...', a()); // 1
a = a.around(function (proceed, handler, args) {
return (proceed() + 1);
});
console.log('\nmodified a ...', a);
console.log('a() ...', a()); // 2
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
(function(d){function f(a){return typeof a==e&&typeof a.call==e&&typeof a.apply==e}function g(a,b){b=null!=b&&b||null;var c=this;return f(a)&&f(c)&&function(){return a.call(b||null!=this&&this||null,c,a,arguments)}||c}var e=typeof d;Object.defineProperty(d.prototype,"around",{configurable:!0,writable:!0,value:g});Object.defineProperty(d,"around",{configurable:!0,writable:!0,value:function(a,b,c){return g.call(a,b,c)}})})(Function);
</script>
This is a Clear Example based on a control timepicker eworld.ui
www.eworldui.net
Having a TimePicker eworld.ui where JavaScript is unreachable from outside, you can't find any js related to those controls. So how can you add a onchange event to the timepicker ?
There is a js function called when you Select a time between all the options that the control offer you. This function is: TimePicker_Up_SelectTime
First you have to copy the code inside this function.
Evaluate...quikwatch...TimePicker_Up_SelectTime.toString()
function TimePicker_Up_SelectTime(tbName, lblName, divName, selTime, enableHide, postbackFunc, customFunc) {
document.getElementById(tbName).value = selTime;
if(lblName != '')
document.getElementById(lblName).innerHTML = selTime;
document.getElementById(divName).style.visibility = 'hidden';
if(enableHide)
TimePicker_Up_ShowHideDDL('visible');
if(customFunc != "")
eval(customFunc + "('" + selTime + "', '" + tbName + "');");
eval(postbackFunc + "();");
}
Now
Using the code that you have saved before reassign the same source code but add whatever you want..
TimePicker_Up_SelectTime = function (tbName, lblName, divName, selTime, enableHide, postbackFunc, customFunc) {
document.getElementById(tbName).value = selTime;
if (lblName != '')
document.getElementById(lblName).innerHTML = selTime;
document.getElementById(divName).style.visibility = 'hidden';
if (enableHide)
TimePicker_Up_ShowHideDDL('visible');
if (customFunc != "")
eval(customFunc + "('" + selTime + "', '" + tbName + "');");
eval(postbackFunc + "();");
>>>>>>> My function >>>>> RaiseChange(tbName);
}
I've added My Function to the function so now I can simulate an onchange event when I select a time.
RaiseChange(...) could be whatever you want.
If you're debugging javascript and want to see how changes to the code affects the page, you can use this Firefox extension to view/alter javascripts:
Execute JS firefox extension:
https://addons.mozilla.org/en-US/firefox/addon/1729
You can change functions like other objects
var a1 = function(){return 1;}
var b1 = a1;
a1 = function(){
return b1() + 1;
};
console.log(a1()); // return 2
// OR:
function a2(){return 1;}
var b2 = a2;
a2 = function(){
return b2() + 1;
};
console.log(a2()); // return 2
Can you not just define it again later on? When you want the change try just redefining it as:
a = function() { return 2; }
const createFunction = function (defaultRealization) {
let realization = defaultRealization;
const youFunction = function (...args) {
return realization(...args);
};
youFunction.alterRealization = function (fn) {
realization = fn;
};
return youFunction;
}
const myFunction = createFunction(function () { return 1; });
console.log(myFunction()); // 1
myFunction.alterRealization(function () { return 2; });
console.log(myFunction()); // 2

Categories

Resources