Object should keep its status - javascript

I am trying to figure out how to put an object to a function and return that
object with its original values.
It's part from my "framework"...
Here an simplified example:
var _objectToFunction = function (obj) {
var F = function () { }
F.prototype = obj
return F
}
var myclass = {
a:"abc",
print: function(){
console.log("i am a func")
},
config: {
path: "c:/bla"
}
}
var fo = _objectToFunction(myclass)
var of = new fo()
of.config.path = "c:/ofpath"
of.z = "zzz"
of.a ="aaa"
console.log(of)
var fo2 = _objectToFunction(myclass)
var of2 = new fo2()
console.log(of2.z)
console.log(of2.a)
console.log(of2.config.path)
The output from console.log(of2.config.path) should "c:/bla", but is "c:/ofpath".
How can I do this right?

You may want to add a constructor (a function that is called, when an instance was created):
var _objectToFunction = function (obj) {
var F = function (...values) {
if( this.constructor) this.constructor(...values);
}
F.prototype = obj
return F
}
So you can create a new config Object for each instance:
var myclass = {
constructor:function(addconf){
this.config=Object.create(this.config);
if(addconf) Object.assign(this.config,addconf);
},
a:"abc",
print: function(){
console.log("i am a func")
},
config: {
path: "c:/bla"
}
}
Now it behaves as wanted.
var parent=_objectToFunction(myclass);
var instance=new parent({ path:"changed"});
Or with standard object funcs:
var instance=Object.create(myclass);
instance.constructor({path:"changed"});

Related

Merging given objects

I am just learning javascript and I need to know how I will go about doing this please:
Task: Merge the given objects into var C
var a = {
name: "Danny"
};
var b = {
getName: function () {
return this.name;
}
};
Output should be danny
var solve = function () {
var C;
var instance = new C();
console.log("Name: "+ instance.getName());
};
solve();
You can use Object.assign() to merge existing objects into any other object. The syntax is:
Object.assign(target, src1, src2, ....);
And, here it is working with your code:
var a = {
name: "Danny"
};
var b = {
getName: function () {
return this.name;
}
};
var C = function() {
Object.assign(this, a, b);
}
var instance = new C();
console.log("Name: "+ instance.getName());

Creating object by using string as a name

My function gets model name as string, I need to create new instance of object based on its name.
ex.:
modelName = 'MockA';
model = new modelName();
this is ofcourse not working. in php i would use
model = new $$modelName
thanks in advance
If MockA is in global scope you can use:
var model = new window[modelName]();
if not then you should reconsider the way you store your models, eg. with an object of models:
var my_models = {
MockA: function() {},
MockB: function() {}
}
and to access
var MockA = my_models.MockA;
// or
var model_name = 'MockA';
var MockA = my_models[model_name];
You can use an object factory or bracket notation.
Sample of code:
// First example: Use a Factory
var MockA = function() {
this.sayHello = function() {
console.log('Hi from MockA ');
};
},
MockB = function() {
this.sayHello = function() {
console.log('Hi from MockB ');
}
},
factory = function(type) {
var obj;
switch (type) {
case 'MockA':
obj = new MockA();
break;
case 'MockB':
obj = new MockB();
break;
}
return obj;
}
var objA = factory('MockA');
objA.sayHello();
var objB = factory('MockB');
objB.sayHello();
// Second example: Using bracket notation
var models = {
BaseMockA: {
sayHello: function() {
console.log('Hi from BaseMockA ');
}
},
BaseMockB: {
sayHello: function() {
console.log('Hi from BaseMockB ');
}
}
};
var baseObjA = Object.create(models['BaseMockA']);
baseObjA.sayHello();
var baseObjB = Object.create(models['BaseMockB']);
baseObjB.sayHello();

JavaScript: Prevent Array.push()

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.

How to json strinfigy a function instance in javascript?

If I have this code
var node = function(n) {
var name = n;
var children = [];
var finished = false;
var failed = false;
this.getName = function() {
return name
};
this.downloadData = function(obj) {
};
this.getChildren = function() {
return children;
};
this.setChildren = function(c) {
Array.prototype.push.apply(children, c);
};
this.isFinished = function() {
return finished;
};
this.setFinished = function() {
finished = true;
}
this.isFailed = function() {
return failed;
}
this.setFailed = function() {
failed = true;
}
};
How can I convert this into an object like:
var a = new node("a");
var j = JSON.stringify(a);
result
{"name":"a","children":[],"finished":false,"failed":false}
thanks
This could be done by implementing the toJSON function.
If an object being stringified has a property named toJSON whose value
is a function, then the toJSON() method customizes JSON
stringification behavior: instead of the object being serialized, the
value returned by the toJSON() method when called will be serialized.
- Mozilla
eg:
var node = function(n) {
var name = n;
var children = [];
var finished = false;
var failed = false;
this.toJson = function toJson() {
return {"name":name ... };
}
}
You need object properties instead of variables.
So, instead of declaring var name = n;, you would declare this.name = n;. Which would make it look something like
var node = function(n) {
this.name = n;
this.children = [];
this.finished = false;
this.failed = false;
///other functions here
}

Assigning defined function to an object attribute in javascript

i have a object in javascript and some already defined functions. but how can i assign those functions to the object attributes. i tried different ways. but no hope.. the snippet is given below
// object
var func = {
a : '',
b : ''
};
// methods
var test1 = function(i) { console.log(i); }
var test2 = function(i) { console.log(i*100); }
i need to assign the test1 to a and test2 to b. i tried like this.
var func = {
a : test1(i),
b : test2(i)
};
obviously the errors i not defined is throwing.. is ther any solution other than the below give sinppet.
var func = {
a : function(i) { test1(i); },
b : function(i) { test2(i); }
};
This does what you're asking:
var test1 = function(i) { console.log(i); }
var test2 = function(i) { console.log(i*100); }
var func = {
a: test1,
b: test2
}
But isn't very good style.
This might be better:
function exampleClass () {}
exampleClass.prototype.a = function(i) { console.log(i); };
exampleClass.prototype.b = function(i) { console.log(i*100); };
var exampleObject = new exampleClass();

Categories