How to wrap Javascript function within function expression? - javascript

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);

Related

functions in object literal javascript

i'm a newbie starting to learn java-script..
const textchanger = function () {
let text = "text that has been changed now"
const picktext = function () {
let element = document.querySelector("h1")
element.textContent = text
return {
callfun: function () {
picktext();
console.log(text);
}
}
}
}
textchanger.fun()
<h1> Getting started </h1>
i'm trying to change the text inside
<h1>Getting started</h1>
but getting the error..
TypeError: textchanger.callfun is not a function
at Object.
It looks like you're experimenting with closures but to do that you need to return the inner function from the function you initially call. You can then assign that returned function to a variable, and then call that.
Here's an example that shows how this works. (The setTimeout is there to show how the same function can be called again with different text, and get a different result.)
// Accept an element, and return a new function
// that accepts some text. `element` will be returned
// along with the inner function so it can be used
function textChanger(element) {
return function (text) {
element.textContent = text;
}
}
// Cache the element
const element = document.querySelector('h1');
// Call `textChanger` with the element as its
// argument, and assign the returned function to
// a variable
const changeText = textChanger(element);
// Call that function with some text
changeText('First text!');
// Call the same function with some different text
setTimeout(changeText, 2000, 'Second text!');
<h1>Getting started</h1>
TextChanger is the function not a plain variable so below code works:
textchanger().callfun()
textchanger is a function, but It doesn't return any thing!
I think you mean this:
const textchanger = function () {
let text = "text that has been changed now";
const picktext = function () {
let element = document.querySelector("h1");
element.textContent = text;
return {
callfun: function () {
picktext();
console.log(text);
}
}
}
return picktext(); // <==== put this line
}
textchanger().callfun();
const textchanger = function () {
let text = "text that has been changed now";
const picktext = function () {
let element = document.querySelector("h1");
element.textContent = text;
return {
callfun: function () {
picktext();
console.log(text);
},
};
};
return picktext(); ==>return picktext() function
};
textchanger(); ==> by calling this the text will be changed

I wanted to make a javascript library function is not working

I wanted to call the run function that should call the other and action will be done on the base of element_id
NGL = {}
NGL.SceneBuilder = function() {
var yamlFile = 'http://example.com/main.yaml'
var parseYaml = function() {
}
var buildScene = function() {
// other code
simulationStarted(element_id);
}
return {
run: function(element_id) {
parseYaml();
buildScene(element_id);
}
}
}
NGL.SceneBuilder.run('#someid');
You're not executing your factory so NGL.SceneBuilder is a function, not an object having the run property. Call the function :
NGL.SceneBuilder = (function() {
...
})(); // <<===
Note also that you forget to declare the element_id parameter in buildScene but maybe is it just for the question.

Javascript concatenate a function similar to how text can be added

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();
}

JavaScript call variable as Object and Function like jQuery

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');
}

change base function behaveiour

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;

Categories

Resources