I'm developing a small framework (in JS) and for esthetic reasons and simplicity I was wondering if there could be a way to implement something like PHP "__invoke".
For example:
var myClass = function(config) {
this.config = config;
this.method = function(){};
this.execute = function() {
return this.method.apply(this, arguments);
}
}
var execCustom = new myClass({ wait: 100 });
execCustom.method = function() {
console.log("called method with "+arguments.length+" argument(s):");
for(var a in arguments) console.log(arguments[a]);
return true;
};
execCustom.execute("someval","other");
Desired way to execute:
execCustom("someval","other");
Any ideas? Thanks.
if you are ready to use JS pattern, you can do this in following way:
var myClass = function(opts) {
return function(){
this.config = opts.config;
this.method = opts.method;
return this.method.apply(this, arguments);
};
};
var execCustom = new myClass({
config:{ wait: 100 },
method:function() {
console.log("called method with "+arguments.length+" argument(s):");
for(var a in arguments) console.log(arguments[a]);
return true;
}});
execCustom("someval","other");
jsbin
this is the best way I can think of
UPDATED VERSION (by op)
var myClass = function(opts) {
var x = function(){
return x.method.apply(x, arguments);
};
x.config = opts.config;
x.method = opts.method;
return x;
};
var execCustom = new myClass({
config:{ wait: 100 },
method:function() {
console.log("called method with "+arguments.length+" argument(s):");
for(var a in arguments) console.log(arguments[a]);
return true;
}});
execCustom("someval","other");
jsbin
Just return a function that will form the public interface:
function myClass(config)
{
var pubif = function() {
return pubif.method.apply(pubif, arguments);
};
pubif.config = config;
pubif.method = function() { };
return pubif;
}
The rest of the code remains the same.
Related
Suppose I have a function called log which simply prints the given string.
Can I refactor my code so both of these function could work?
log("needsChange").doSomethingWithTheStringBeforePrintingIt();
log("perfectStringToPrint");
You can do something similar with nested class logics:
var log = (function() {
//Class
var _log = (function() {
function _log(message) {
this.message = message;
}
_log.prototype.doSomethingWithTheStringBeforePrintingIt = function() {
this.message = this.message.split("").reverse().join("");
return this;
};
_log.prototype.capitalizeFirstWord = function() {
this.message = this.message[0].toUpperCase() + this.message.substr(1);
return this;
};
_log.prototype.print = function() {
return this.message;
};
return _log;
}());
//Instancer function
return function log(message) {
//Return instance of class
return new _log(message);
};
})();
//Test
console.log(log("needsChange")
.doSomethingWithTheStringBeforePrintingIt()
.capitalizeFirstWord()
.print(), log("perfectStringToPrint")
.print());
If you are comfortable with promises, then you can do something like this:
var logger = (function() {
//Class
var _log = (function() {
function _log(message) {
var _this = this;
this.message = message;
this.promise = null;
this.promises = [];
this.promise = Promise.all(this.promises).then(function(values) {
console.log(_this.message); // [3, 1337, "foo"]
});
}
_log.prototype.reverse = function() {
var self = this;
this.promises.push(new Promise(function(resolve, reject) {
setTimeout(resolve, 0, (function() {
self.message = self.message.split("").reverse().join("");
})());
}));
return this;
};
_log.prototype.capitalizeFirst = function() {
var self = this;
this.promises.push(new Promise(function(resolve, reject) {
setTimeout(resolve, 0, (function() {
self.message = self.message[0].toUpperCase() + self.message.substr(1);
})());
}));
return this;
};
return _log;
}());
//Instancer function
return function log(message) {
//Return instance of class
return new _log(message);
};
})();
//Test
logger("needsChange").reverse().capitalizeFirst().reverse(); //Capitalizes last letter
logger("perfectStringToPrint");
This removes the need for a .print call.
I have made a library to solve this issue
https://github.com/omidh28/clarifyjs
I'm constructing a Builder in JavaScript, and I'm not sure how builders normally handle undefined values for optionals. I would like to think that the Builder doesn't append the optional field to the object if the field is undefined. Is that acceptable for a Builder? If not, what would be alternatives?
Here is a sample of the first implementation where the builder doesn't append an undefined optional:
Builder:
function Thing(required1, required2, required3) {
//check required params
var fields = {
required1: required1,
required2: required2,
required3: required3
};
var _withOptionalParam = function(param) {
if(!param) { return this; } //exit function early if param is undefined
fields.param = param;
return this;
};
var _build = function() {
var result = fields;
return result;
};
var builder = {
withOptionalParam: _withOptionalParam,
build: _build
};
return builder;
}
In action:
var thing = new Thing("foo","bar","baz").withOptionalParam(undefined).build();
//'thing' should be
// {
// required1:"foo",
// required2:"bar",
// required3:"baz"
// };
//
Thanks in advance!
I think you are losing the context of this in your _withOptinalParam function. You could bind you fields object to it as the this context.
function Thing(required1, required2, required3) {
//check required params
var fields = {
required1: required1,
required2: required2,
required3: required3
};
var _withOptionalParam = function(param) {
if(!param) { return this; } //exit function early if param is undefined
fields.param = param;
return this;
};
var _build = function() {
var result = fields;
return result;
};
var builder = {
withOptionalParam: _withOptionalParam.bind(fields),
build: _build
};
return builder;
}
var thing = new Thing("foo","bar","baz").withOptionalParam(undefined);
console.log( thing );
//'thing' should be
// {
// required1:"foo",
// required2:"bar",
// required3:"baz"
// };
//
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
I have a sealed object with an array member on which I want to prevent direct pushes.
var myModule = (function () {
"use strict";
var a = (function () {
var _b = {},
_c = _c = "",
_d = [];
Object.defineProperty(_b, "c", {
get: function () { return _c; }
});
Object.defineProperty(_b, "d", {
get { return _d; }
});
_b.addD = function (newD) {
_d.push(newD);
};
Object.seal(_b);
return _b;
}());
var _something = { B: _b };
return {
Something: _something,
AddD: _b.addD
};
}());
myModule.Something.c = "blah"; // doesn't update = WIN!!
myModule.AddD({}); // pushed = WIN!
myModule.Something.d.push({}); // pushed = sadness
How can I prevent the push?
UPDATE:
Thanks for all the thoughts. I eventually need the JSON to send to the server. It looks like I might need to use an object for the array then figure out a way to generate and return the JSON needed, or change _something to use .slice(). Will play and report.
you could override the push method:
var _d = [];
_d.__proto__.push = function() { return this.length; }
and when you need to use it in your module, call Array.prototype.push:
_b.addD = function (newD) {
Array.prototype.push.call(_d, newD);
};
I haven't done any performance tests on this, but this certainly helps to protect your array.
(function(undefined) {
var protectedArrays = [];
protectArray = function protectArray(arr) {
protectedArrays.push(arr);
return getPrivateUpdater(arr);
}
var isProtected = function(arr) {
return protectedArrays.indexOf(arr)>-1;
}
var getPrivateUpdater = function(arr) {
var ret = {};
Object.keys(funcBackups).forEach(function(funcName) {
ret[funcName] = funcBackups[funcName].bind(arr);
});
return ret;
}
var returnsNewArray = ['Array.prototype.splice'];
var returnsOriginalArray = ['Array.prototype.fill','Array.prototype.reverse','Array.prototype.copyWithin','Array.prototype.sort'];
var returnsLength = ['Array.prototype.push','Array.prototype.unshift'];
var returnsValue = ['Array.prototype.shift','Array.prototype.pop'];
var funcBackups = {};
overwriteFuncs(returnsNewArray, function() { return []; });
overwriteFuncs(returnsOriginalArray, function() { return this; });
overwriteFuncs(returnsLength, function() { return this.length; });
overwriteFuncs(returnsValue, function() { return undefined; });
function overwriteFuncs(funcs, ret) {
for(var i=0,c=funcs.length;i<c;i++)
{
var func = funcs[i];
var funcParts = func.split('.');
var obj = window;
for(var j=0,l=funcParts.length;j<l;j++)
{
(function() {
var part = funcParts[j];
if(j!=l-1) obj = obj[part];
else if(typeof obj[part] === "function")
{
var funcBk = obj[part];
funcBackups[funcBk.name] = funcBk;
obj[part] = renameFunction(funcBk.name, function() {
if(isProtected(this)) return ret.apply(this, arguments);
else return funcBk.apply(this,arguments);
});
}
})();
}
}
}
function renameFunction(name, fn) {
return (new Function("return function (call) { return function " + name +
" () { return call(this, arguments) }; };")())(Function.apply.bind(fn));
};
})();
You would use it like so:
var myArr = [];
var myArrInterface = protectArray(myArr);
myArr.push(5); //Doesn't work, but returns length as expected
myArrInterface.push(5); //Works as normal
This way, you can internally keep a copy of the interface that isn't made global to allow your helper funcs to modify the array as normal, but any attempt to use .push .splice etc will fail, either directly, or using the .bind(myArr,arg) method.
It's still not completely watertight, but a pretty good protector. You could potentially use the Object.defineProperty method to generate protected properties for the first 900 indexes, but I'm not sure of the implications of this. There is also the method Object.preventExtensions() but I'm unaware of a way to undo this effect when you need to change it yourself
Thank you, dandavis!
I used the slice method:
var myModule = (function () {
"use strict";
var a = (function () {
var _b = {},
_c = _c = "",
_d = [];
Object.defineProperty(_b, "c", {
get: function () { return _c; }
});
Object.defineProperty(_b, "d", {
get { return _d.slice(); } // UPDATED
});
_b.updateC = function (newValue) {
_c = newValue;
};
_b.addD = function (newD) {
_d.push(newD);
};
Object.seal(_b);
return _b;
}());
var _something = { B: _b };
return {
Something: _something,
AddD: _b.addD
};
}());
myModule.Something.c = "blah"; // doesn't update = WIN!!
myModule.AddD({}); // pushed = WIN!
myModule.Something.d.push({}); // no more update = happiness
This allows me to protect from direct push calls enforcing some logic.
Trying to implement singleton pattern in javascript following some tutorials. Just wondering if there is any other way to implement the same ?
var singleton = (function(){
var getInstance; //private variable
var createWidget = function(){
var todayDate = new Date(); //private
var addCSS = function(){
console.log('THis is my css function');
};
var getDropDownData = function(){
console.log('This is my getDropDownData function');
};
return {
getDropDownData : getDropDownData,
addCSS: addCSS
};
};
return {
getInstance: function(){
if(!getInstance) {
getInstance = createWidget();
}
return getInstance;
}
};
})();
var obj = singleton.getInstance();
Implementing it by running anonymous function at onLoad and assiging it to some variable. Can we implement it without running this function at onLoad ?
You could always write a function to abstract away the boilerplate for writing singletons. For example this is what I would do:
function singleton(prototype) {
var instance = null;
return {
getInstance: function () {
if (instance === null) {
var Instance = prototype.init || function () {};
Instance.prototype = prototype;
instance = new Instance;
} return instance;
}
};
}
Then you can use this function to create singletons as follows:
var Widget = singleton({
init: function () {
var todayDate = new Date; // private
},
addCSS: function () {
console.log("This is my addCSS function.");
},
getDropDownData: function () {
console.log("This is my getDropDownData function.");
}
});
After that you use the singleton as you normally would:
var widget = Widget.getInstance();
Hope that helps.
i'm practicing with Javascript Inheritance, my first try is following code:
var base_class = function()
{
var _data = null;
function _get() {
return _data;
}
this.get = function() {
return _get();
}
this.init = function(data) {
_data = data;
}
}
var new_class = function() {
base_class.call(this);
var _data = 'test';
function _getData() {
return this.get();
}
this.getDataOther = function() {
return _getData();
}
this.getData = function() {
return this.get();
}
this.init(_data);
}
new_class.prototype = base_class.prototype;
var instance = new new_class();
alert(instance.getData());
alert(instance.getDataOther());
to that point i am really happy with my solution, but there is one problem
that i dont get resolved.
the "getDataOther" method don`t return the stored data from the base class,
because i cannot access the public "get" class from the protected "_getData" method in the new_class.
How can i get that running ?
Thanks in advance.
Ps.: Please excuse my poor English
If you comment out the this.init function (which overwrites the base_class _data field) and make the new_class's getData function just return _data, you should be able to get distinct variables.
var base_class = function()
{
var _data = null;
function _get() {
return _data;
}
this.get = function() {
return _get();
}
this.init = function(data) {
_data = data;
}
}
var new_class = function() {
var self = this; //Some browsers require a separate this reference for
//internal functions.
//http://book.mixu.net/ch4.html
base_class.call(this);
var _data = 'test';
function _getData() {
return self.get();
}
this.getDataOther = function() {
return _getData();
}
this.getData = function() {
return _data; //Changed this line to just return data
//Before, it did the same thing as _getData()
}
//this.init(_data); //Commented out this function (it was changing the base_class' data)
}
new_class.prototype = base_class.prototype;
var instance = new new_class();
alert(instance.getData());
alert(instance.getDataOther());
Your english is fine by the way :)