How to create a method call from a string without using eval - javascript

Can anyone advise me how to create a method call using a string and without using eval? Please note that methodCall cannot be hard-coded and has to be dynamic. methodCall will be created dynamically.
In the following example this refers to a Backbone view, e.g.
var amount = this.model.get('amount');
var $amount = this.$el.find('.amount');
var methodCall = 'this.parentController.parentController.addBinding';
//then need to call the method with args
methodCall('amount',$amount);
I first thought this would work:
this['controller']['parentController']['view']['addBinding'](amount, $amount);
However I came to realise that this would not be dynamic either. Does anyone have a solution?

As noted in this answer, Multiple level attribute retrieval using array notation from a JSON object, you can traverse the hierarchy of objects with something like this:
function findprop(obj, path) {
var args = path.split('.'), i, l;
for (i=0, l=args.length; i<l; i++) {
if (!obj.hasOwnProperty(args[i]))
return;
obj = obj[args[i]];
}
return obj;
}
You could then give your view/model/collection a method to apply an arbitrary path:
var V = Backbone.View.extend({
dyncall: function(path) {
var f = findprop(this, path);
if (_.isFunction(f))
return f.call(this, 'your args');
}
});
var v = new V();
v.dyncall('parentController.parentController.addBinding');
And a demo http://jsfiddle.net/nikoshr/RweEC/
A little more flexibility on passing the arguments :
var V = Backbone.View.extend({
dyncall: function() {
var f = findprop(this, arguments[0]);
if (_.isFunction(f))
f.apply(this, _.rest(arguments, 1));
}
});
var v = new V();
v.dyncall('parentController.parentController.addBinding', 'your arguments', 'another arg');
http://jsfiddle.net/nikoshr/RweEC/1/

Related

How to create multiple different instaneces simillarly to jQuery?

What I would like is to use _h like $ jQuery. Every time I use _h i want to have new instance of Helper class, which would hold selected element, do stuff with them and so on.
The problem is that _h does not creates new instance of class, but rather use already created one.
I assumed if I use it like that:
var obj1 = _h('p');
var obj2 = _h('#testDiv');
I would have two different instances of class. However both instances store the same elements and seems to point to the same instance.
var _h = (function(){
var Helper = function(query){
if(window === this)
return new Helper(query);
this.Get.call(this, query);
this._allCurrentElements = [];
}
Helper.prototype.Get = function(query){
var els = document.querySelectorAll(query);
for (var i = 0; i < els.length; i++) {
_allCurrentElements.push(els[i])
};
return this;
}
Helper.prototype.AddClass = function(cl) {
// do stuff
return this;
}
Helper.prototype.RemoveClass = function(cl) {
// do stuff
return this;
}
// more methods
//return Helper;
//return Helper();
return new Helper();
})();
So if someone could point me that I am doing wrong, I would really appreciate that.
Edit: If I don't wrap it in IFFE, don't assign to _h var and call var t = Helper('p'), then it behaves as expected
(function(){})() is called an IIFE (Immediately Invoked Function Expression). Which means, you are declaring a anonymous function and invoking it in a single step. The return value of the IIFE is stored in _h.
When you return new Helper();, _h contains an instance of Helper.
When you return Helper, you are returning the constructor of the Helper class. You will have to use new _h() create new Helper object.
What you need is a wrapper function that will take the arguments, create a new Helper object and return it.
Try
var _h = (function(){
var Helper = function(query){
if(window === this)
return new Helper(query);
this.Get.call(this, query);
this._allCurrentElements = [];
}
Helper.prototype.Get = function(query){
var els = document.querySelectorAll(query);
for (var i = 0; i < els.length; i++) {
_allCurrentElements.push(els[i])
};
return this;
}
Helper.prototype.AddClass = function(cl) {
// do stuff
return this;
}
Helper.prototype.RemoveClass = function(cl) {
// do stuff
return this;
}
// more methods
return function (query) {
return new Helper(query);
};
})();
Update 1:
In Helper.prototype.Get, _allCurrentElements is a global variable. You need to use this._allCurrentElements.
Also, you need to initialize this._allCurrentElements = []; before calling this.Get
Working Example - https://jsfiddle.net/ucqgnbne/
Update 2
As #Bergi commented, returning Helper will work since you are using if(window === this) return new Helper(query);.

Preserve function property when created with "bind"

I have a function that looks like this:
var tempFun = function() {
return 'something';
}
tempFun.priority = 100;
Now I'm pushing it to an array and binding another object to it in the process like this:
var funArray = [];
var newObj = {};
funArray.push( tempFun.bind(newObj) );
and after this, I would like to acces the function's property like this:
funArray[0].priority
but it returns undefined. Is there some way to preserve the property on the function while binding a new object to it?
No, but you could write a function to do this yourself;
Function.prototype.bindAndCopy = function () {
var ret = this.bind.apply(this, arguments);
for (var x in this) {
if (this.hasOwnProperty(x)) {
ret[x] = this[x];
}
}
return ret;
};
... which you could then use via;
var funArray = [];
var newObj = {};
funArray.push( tempFun.bindAndCopy(newObj) );
No. Bind returns a new function, which "wraps" around the original one. All you can do is copy the properties on this new function:
var boundFun = tempFun.bind(newObj)
boundFun.priority = tempFun.priority;
funArray.push( boundFun );
If you want the properties to be in sync (changes in one visible on the other) you can do:
Object.defineProperty(boundFun, 'priority', {
get : function () { return tempFun.priority; },
set : function (val) { tempFun.priority = val; }
});
From MDN:
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
Hence, .bind() won't be useful for what you're trying to achieve. Besides using jQuery mappers or rewriting your code to use .prototype, a solution that I can think of is:
var obj = {};
for (var i in tempFun) {
if (tempFun.hasOwnProperty(i)) obj[i] = tempFun[i];
}

Dynamically creating a new javascript class from an existing object

Say I have the following code:
var album = new MyObject('album');
Assume that when the object is constructed, a bunch of properties relative to only albums are loaded via AJAX. Would it be possible to create an Album class so that at a later point, I may just do this:
var anotherAlbum = new Album();
The Album constructor would automatically set the properties that are unique to album objects, based on what was loaded when creating MyObject('album')
JavaScript is prototypal, not classical, so if you think in terms of classes, you're doing it wrong.
You don't have to use the new operator at all. You can create a new object using the object literal:
var myObject = {attr1: 'val1', attr2: 'val2'};
Then you can create a new instance of that object:
var mySecondObject = Object.create(myObject);
Now you can change the attributes of mySecondObject, and if it has methods you can overload them just as easily:
mySecondObject.attr1 = "Hello";
mySecondObject.attr2 = function() {
return "World!";
};
And then mySecondObject will of course have all the properties that you gave myObject at creation.
Be aware that this is a simple version, and that this leaves all attributes 'public'. If you need some privacy, it can be achieved by adding some functions to the mix. It's a bit more complicated though, so let me know if you're interested...
JavaScript "classes", just like any other object, can be dynamically created. So, yes, this can be done.
You would do something like this in the code handling the AJAX response (assuming that the AJAX response was providing the name of the new "class", and it's in a variable called newClassName):
window[newClassName] = function() {
// New class name constructor code
}
window[newClassName].prototype = {
someProperty: "someValue",
someMethod: function(a, b) {
},
someOtherMethod: function(x) {
}
}
This is actually the only for of inheritance that JavaScript has. JavaScript has prototypal inheritance (which can be used to recreate classical inheritance). That means that inheritance is from another object, not a class definition.
To create an object that has all the properties of another object is simple:
function Album() {
// do whatever initialization you need to here, all the properties of album
// are available on 'this'
// e.g.,
doSomething(this.albumName);
}
Album.prototype = album;
var anotherAlbum = new Album();
You can use Douglas Crockford's Functional Inheritance Pattern. Code from Javascript Good Parts book
var mammal = function (spec) {
var that = {};
that.get_name = function ( ) {
return spec.name;
};
that.says = function ( ) {
return spec.saying || '';
};
return that;
};
var myMammal = mammal({name: 'Herb'});
var cat = function (spec) {
spec.saying = spec.saying || 'meow';
var that = mammal(spec);
that.purr = function (n) {
var i, s = '';
for (i = 0; i < n; i += 1) {
if (s) {
s += '-';
}
s += 'r';
}
return s;
};
that.get_name = function ( ) {
return that.says( ) + ' ' + spec.name +
' ' + that.says( );
return that;
};
var myCat = cat({name: 'Henrietta'});
It uses functions to decorate existing javascript objects with new functions and properties. Like this you can add new functions and properties on the fly to your existing object
You can do this
var NewClass=function(){
this.id=null;
this.name=null;
this.show=function(){
alert(this.id+" "+this.name;
}
}
NewClass.prototype.clear=function(){
this.id=null;
this.name=null;
};
...
var ins1=new NewClass();
var ins2=new NewClass();

JavaScript Object Id

Do JavaScript objects/variables have some sort of unique identifier? Like Ruby has object_id. I don't mean the DOM id attribute, but rather some sort of memory address of some kind.
If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:
// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
return objIdMap.get(object);
}
var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3
Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.
No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:
(function() {
var id = 0;
function generateId() { return id++; };
Object.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
return newId;
};
})();
That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch function as others have suggested.
Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.
var __next_objid=1;
function objectId(obj) {
if (obj==null) return null;
if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
return obj.__obj_id;
}
I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:
var objectId = (function () {
var allObjects = [];
var f = function(obj) {
if (allObjects.indexOf(obj) === -1) {
allObjects.push(obj);
}
return allObjects.indexOf(obj);
}
f.clear = function() {
allObjects = [];
};
return f;
})();
You can get any object's ID by calling objectId(obj). Then if you want the id to be a property of the object, you can either extend the prototype:
Object.prototype.id = function () {
return objectId(this);
}
or you can manually add an ID to each object by adding a similar function as a method.
The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the allObjects array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can do objectId.clear() to clear the allObjects and let the GC do its job (but from that point the object ids will all be reset).
const log = console.log;
function* generateId() {
for(let i = 0; ; ++i) {
yield i;
}
}
const idGenerator = generateId();
const ObjectWithId = new Proxy(Object, {
construct(target, args) {
const instance = Reflect.construct(target, args);
instance['id'] = idGenerator.next().value;
return instance;
}
})
const myObject = new ObjectWithId({
name: '##NativeObject'
});
log(myObject.id);

How can I construct an object using an array of values for parameters, rather than listing them out, in JavaScript?

Is this possible? I am creating a single base factory function to drive factories of different types (but have some similarities) and I want to be able to pass arguments as an array to the base factory which then possibly creates an instance of a new object populating the arguments of the constructor of the relevant class via an array.
In JavaScript it's possible to use an array to call a function with multiple arguments by using the apply method:
namespace.myFunc = function(arg1, arg2) { //do something; }
var result = namespace.myFunc("arg1","arg2");
//this is the same as above:
var r = [ "arg1","arg2" ];
var result = myFunc.apply(namespace, r);
It doesn't seem as if there's anyway to create an instance of an object using apply though, is there?
Something like (this doesn't work):
var instance = new MyClass.apply(namespace, r);
Try this:
var instance = {};
MyClass.apply( instance, r);
All the keyword "new" does is pass in a new object to the constructor which then becomes the this variable inside the constructor function.
Depending upon how the constructor was written, you may have to do this:
var instance = {};
var returned = MyClass.apply( instance, args);
if( returned != null) {
instance = returned;
}
Update: A comment says this doesn't work if there is a prototype. Try this.
function newApply(class, args) {
function F() {
return class.apply(this, args);
}
F.prototype = class.prototype;
return new F();
}
newApply( MyClass, args);
Note that
new myClass()
without any arguments may fail, since the constructor function may rely on the existence of arguments.
myClass.apply(something, args)
will fail in many cases, especially if called on native classes like Date or Number.
I know that "eval is evil", but in this case you may want to try the following:
function newApply(Cls, args) {
var argsWrapper = [];
for (var i = 0; i < args.length; i++) {
argsWrapper.push('args[' + i + ']');
}
eval('var inst = new Cls(' + argsWrapper.join(',') + ');' );
return inst;
}
Simple as that.
(It works the same as Instance.New in this blog post)
Hacks are hacks are hacks, but perhaps this one is a bit more elegant than some of the others, since calling syntax would be similar to what you want and you wouldn't need to modify the original classes at all:
Function.prototype.build = function(parameterArray) {
var functionNameResults = (/function (.{1,})\(/).exec(this.toString());
var constructorName = (functionNameResults && functionNameResults.length > 1) ? functionNameResults[1] : "";
var builtObject = null;
if(constructorName != "") {
var parameterNameValues = {}, parameterNames = [];
for(var i = 0; i < parameterArray.length; i++) {
var parameterName = ("p_" + i);
parameterNameValues[parameterName] = parameterArray[i];
parameterNames.push(("parameterNameValues." + parameterName));
}
builtObject = (new Function("parameterNameValues", "return new " + constructorName + "(" + parameterNames.join(",") + ");"))(parameterNameValues);
}
return builtObject;
};
Now you can do either of these to build an object:
var instance1 = MyClass.build(["arg1","arg2"]);
var instance2 = new MyClass("arg1","arg2");
Granted, some may not like modifying the Function object's prototype, so you can do it this way and use it as a function instead:
function build(constructorFunction, parameterArray) {
var functionNameResults = (/function (.{1,})\(/).exec(constructorFunction.toString());
var constructorName = (functionNameResults && functionNameResults.length > 1) ? functionNameResults[1] : "";
var builtObject = null;
if(constructorName != "") {
var parameterNameValues = {}, parameterNames = [];
for(var i = 0; i < parameterArray.length; i++) {
var parameterName = ("p_" + i);
parameterNameValues[parameterName] = parameterArray[i];
parameterNames.push(("parameterNameValues." + parameterName));
}
builtObject = (new Function("parameterNameValues", "return new " + constructorName + "(" + parameterNames.join(",") + ");"))(parameterNameValues);
}
return builtObject;
};
And then you would call it like so:
var instance1 = build(MyClass, ["arg1","arg2"]);
So, I hope those are useful to someone - they allow you to leave the original constructor functions alone and get what you are after in one simple line of code (unlike the two lines you need for the currently-selected solution/workaround.
Feedback is welcome and appreciated.
UPDATE: One other thing to note - try creating instances of the same type with these different methods and then checking to see if their constructor properties are the same - you may want that to be the case if you ever need to check the type of an object. What I mean is best illustrated by the following code:
function Person(firstName, lastName) {
this.FirstName = firstName;
this.LastName = lastName;
}
var p1 = new Person("John", "Doe");
var p2 = Person.build(["Sara", "Lee"]);
var areSameType = (p1.constructor == p2.constructor);
Try that with some of the other hacks and see what happens. Ideally, you want them to be the same type.
CAVEAT: As noted in the comments, this will not work for those constructor functions that are created using anonymous function syntax, i.e.
MyNamespace.SomeClass = function() { /*...*/ };
Unless you create them like this:
MyNamespace.SomeClass = function SomeClass() { /*...*/ };
The solution I provided above may or may not be useful to you, you need to understand exactly what you are doing to arrive at the best solution for your particular needs, and you need to be cognizant of what is going on to make my solution "work." If you don't understand how my solution works, spend time to figure it out.
ALTERNATE SOLUTION: Not one to overlook other options, here is one of the other ways you could skin this cat (with similar caveats to the above approach), this one a little more esoteric:
function partial(func/*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
}
Function.prototype.build = function(args) {
var constructor = this;
for(var i = 0; i < args.length; i++) {
constructor = partial(constructor, args[i]);
}
constructor.prototype = this.prototype;
var builtObject = new constructor();
builtObject.constructor = this;
return builtObject;
};
Enjoy!
what about a workaround?
function MyClass(arg1, arg2) {
this.init = function(arg1, arg2){
//if(arg1 and arg2 not null) do stuff with args
}
init(arg1, arg2);
}
So how you can:
var obj = new MyClass();
obj.apply(obj, args);
One possibility is to make the constructor work as a normal function call.
function MyClass(arg1, arg2) {
if (!(this instanceof MyClass)) {
return new MyClass(arg1, arg2);
}
// normal constructor here
}
The condition on the if statement will be true if you call MyClass as a normal function (including with call/apply as long as the this argument is not a MyClass object).
Now all of these are equivalent:
new MyClass(arg1, arg2);
MyClass(arg1, arg2);
MyClass.call(null, arg1, arg2);
MyClass.apply(null, [arg1, arg2]);

Categories