Assume I have executed this js code:
var container=function() {
//do something
}
container.a=function {
//do something 2
}
container.b='34'
Here, in order to change container.a function for example I need to do:
container.a=function() {
//do something 3
}
How do I change the function container() ?
You just assign a function to the variable:
container = function() {
//do something
};
This of course means that you get a new function object, which doesn't have the a and b properties. If you want to keep them, you have to copy them to the new function:
var temp = function() {
//do something
};
temp.a = container.a;
temp.b = container.b;
container = temp;
Related
I would like to add a wrapper function to one of my functions to show extra information.
Below is my wrapper function:
var wrap = function(functionToWarp, before) {
var wrappedFunction = function() {
if (before) before.apply(this, arguments);
result = functionToWrap.apply(this, arguments);
return result;
}
return wrappedFunction;
}
var beforeFunc = function(){
// print extra infos before functionToWarp() triggers.
}
and my function _printSth to wrap:
var Printer = function () {
this._printSth = function (input) {
// print something from input...
}
}
Printer._printSth = wrap(Printer._printSth, beforeFunc);
I have tried to wrap Printer._printSth by calling
Printer._printSth = wrap(Printer._printSth, beforeFunc); or similar codes but failed.
How should I declare my _printSth() to be able to be wrapped?
You could write
function Printer() {
this._printSth = function (input) {
// print something from input...
};
this._printSth = wrap(this._printSth, beforeFunc);
}
or
function Printer() {
this._printSth = wrap(function (input) {
// print something from input...
}, beforeFunc);
}
but that's equivalent to simply writing
function Printer() {
this._printSth = function (input) {
beforeFunc(input);
// print something from input...
};
}
Assuming you rather might want to wrap the method on a specific instance, you'd do
const p = new Printer();
p._printSth = wrap(p._printSth, beforeFunc);
Altering a method is done like that:
Printer.prototype._printSth = wrap(Printer.prototype._printSth, beforeFunc);
In javscript we can do this
var text = "the original text";
text+=";Add this on";
If a library has a function already defined (e.g)
//In the js library
library.somefunction = function() {...};
Is there a way to add something on so that I can have two functions run?
var myfunction = function() {...};
Something like:
library.somefunction += myfunction
So that both myfunction() and the original library.somefunction() are both run?
You can use this kind of code (leave scope empty to use default scope):
var createSequence = function(originalFn, newFn, scope) {
if (!newFn) {
return originalFn;
}
else {
return function() {
var result = originalFn.apply(scope || this, arguments);
newFn.apply(scope || this, arguments);
return result;
};
}
}
Then:
var sequence = createSequence(library.somefunction, myFunction);
I think what you want to create is a Hook (function) - you want to call library.somefunction but add a bit of your own code to run before. If that's the case, you can make your myfunction either call or return the library function after it's done with your bit of code.
var myfunction = function() {
// your code
// ...
return library.somefunction();
}
I'm trying to create a library for mobile and I want to be able to call the object as function and object like jquery does.
Example:
var test = function(elm) {
this.ajax = function(opt) { ... }
if ( elm ) {
var elms = document.querySelectorAll(elm);
}
}
and I want to be able to call it like this:
test("#id");
and like this:
test.ajax(opts);
LE:
Thank you guys for your fast responses!
In JavaScript, a function is actually just an object with code attached.
So instead of a plain object:
var test = {};
test.ajax = function() { /* ajax */ };
... use a function:
var test = function() { /* test */ };
test.ajax = function() { /* ajax */ };
In both cases, you can access test.ajax. The extra thing with the function is that you can call test.
Or mabye something like this:
Object.prototype.Test = function( method ) {
var method = method || null;
var elms = null;
/* Methods */
this.ajax = function(opt){
console.log('You called ajax method with options:');
console.log(opt);
}
/* Logic */
if (method in this) this[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
else {
try {
elms = document.querySelectorAll(method);
}
catch(e) {
console.log(e.message);
}
}
}
window.onload = function() {
Test('ajax', {'url':'testurl.com'});
Test('#aid');
}
So I was wondering if it is possible to access a variable (which has a value of function) from outside the scope. I have code that goes something like this:
function parentFunction(){
var childFunction = function() {
// do something
}
}
$(function(){
// need to access childFunction() here.
});
var childFunction;
function parentFunction(){
childFunction = function() {
// do something
}
}
$(function(){
childFunction();
});
No, you do not. The only way to achieve this is to make the desired childFunction an attribute of parentFunction:
var parentFunction = (function(){
var actualParentFunction = function(){
this.childFunction = function() {
// do something
};
}
return new actualParentFunction();
})();
At which point you can do:
parentFunction.childFunction();
Is there a way to call a JavaScript function if a javascript variable changes values using jQuery?
Something to the extend of -
var test = 1;
test = 2; // calls a javascript function
test = 3; // calls a javascript function
This way I wouldn't have to add an onchange event to so many different functions.
(Something seems a bit carelessly planned in your code if you need functionality like that)
The easiest way to add that feature is to create a function for updating your variable, that also calls whatever other function you want to.
Instead of:
var test = 1;
test = 2; // calls a javascript function
test = 3; // calls a javascript function
You do:
var test = 1;
function set_test(newval) {
test = newval;
my_callback(); // this is whatever you wanted to call onChange
}
set_test(2);
set_test(3);
try this, it's real variable change event:
var book = {
_year: 2004,
edition: 1
};
Object.defineProperty(book, "year", {
get: function(){
return this._year;
},
set: function(newValue){
this._year=newValue;
this.edition=newValue-2004;
alert(this._year);
alert(this.edition);
}
});
book.year=2017
// will alert 2017 and 13
No, there is not, just polling with setInterval or setTimeout or callbacks. Events only apply to DOM. I'd suggest that you try to go with callbacks and do things like this:
function foo(data, callback)
{
// do things with data
callback(data);
}
function bar(data)
{
console.log('callback can has', data);
}
foo('baz', bar);
It's a rough example, but should give you the idea.
One option is to wrap your data into a heavier object.
var Watching = function(){
var a;
this.getA(){
return a;
};
this.setA(value){
a = value;
this.trigger('watch');
};
his.watchA(callback){
this.bind('watch', callback);
};
};
var obj = new Watching();
obj.watchA(function(){ alert('changed'); });
obj.setA(2);
This doesn't answer your question exactly, but it may solve your problem:
make your variable as html content of an element, then use jQuery change() event
<script>
document.write("<div id='test'>"+test+"</div>";
$("#test").change(function(){//your script here});
</script>
You can create a class to be notified when your variable changed.
this is the class:
class ListeningVariable {
constructor(val, changeHandler) {
this.val = val;
this.changeHandler = changeHandler
}
set value(val) {
if (this.val !== val) {
this.changeHandler(val);
}
this.val = val;
}
changeHandler(val) {}
}
Then you can create an instance of this class instead of your variable:
let myVar = new ListeningVariable(25/*initialize*/, function(val) {
console.log("variable Changed to:", val);
}/*handler function*/);
And when you want to change your variable, just use this code:
myVar.value = 20; // calls the changeHandler function
myVar.value = 20; // does't call the changeHandler function
myVar.value = 40; // calls the changeHandler function
You can do something like this with setting intervals to keep track of change:
var dataToChange = 1;
var key = dataToChange;
var int = setInterval(() => {
if (dataToChange != key) {
console.log('changed'); /// if data changes
clearInterval(int);
} else {
console.log('nothing changed'); /// while nothing changes
}
}, 3000);
setTimeout(() => {
///// supposedly this is when the variable changes
dataToChange = 2;
}, 9000);
The below function will poll for changes in the test variable every 5 seconds:
// initialize test variable globally
var test = 1;
// global variable to store the previous value of test
// which is updated every 5 seconds
var tmp = test;
setInterval("pollForVariableChange()", 5000);
function pollForVariableChange() {
if (tmp != test) {
alert('Value of test has changed to ' + test);
}
tmp = test;
}