How do I get access to the properties or method of the main object, from sub-obiect level two (sub3). If possible I would like to avoid solutions chaining return this.
Obj = function () {};
Obj.prototype = {
name: 'name',
main: function(){
console.log(this.name);
},
subobject: {
sub2: function () {
console.log(this);
},
sub3: function () {
console.log(this.name); // How access to Obj.name ??
}
}
}
o = new Obj();
o.main(); // return name
o.subobject.sub2(); // return subobject
o.subobject.sub3(); // return undefined
With your current syntax, you can't. Because for sub2 and sub3, the this variable is Obj.prototype.subobject.
You have multiple choice:
The obvious one: don't use a suboject.
Create subobject, sub2 and sub3 in the constructor
Obj = function() {
var self = this;
this.subobject = {
sub1: function() { console.log(self); }
}
}
Use bind at each call:
o.subobject.sub2.bind(o)();
Related
I want to add functions to JSON Objects, but I can't find function for assigning to all objects, only to one.
This code works with Arrays:
Object.defineProperty(Array.prototype, 'random', {
value: () => {
return this[Math.floor(Math.random() * this.length)];
},
});
I've also found this code:
const obj = {name: 'Bob'};
obj.fullName = function() { return this.name }
But that one only works for specific object, not all of them.
Is it event possible to write global functions for all JSON Objects, and if is, then how to do it?
You could add the function to Object.prototype. Note that this is not considered a very good practice because it could impact the rest of the code (like shown in the comments):
Object.prototype.fullName = function() { return this.name; };
const obj = { name: 'Bob' };
console.log(obj.fullName());
You should consider doing this instead:
const baseObject = { fullName: function() { return this.name; } };
const obj = Object.create(baseObject, { name: { value: 'Bob', writable: true } });
console.log(obj.fullName());
And if your target runtime (browser?) supports ECMAScript 6, you could also create a dedicated class for this:
class MyClass {
constructor(name) {
this.name = name;
}
fullName() { return this.name; }
}
const bob = new MyClass('Bob');
console.log(bob.fullName());
Finally, the class syntax for ECMAScript 5:
function MyClass(name) {
this.name = name;
}
MyClass.prototype.fullName = function() { return this.name; }
const bob = new MyClass('Bob');
console.log(bob.fullName());
Function.prototype.bind = function (obj) {
const self = this;
console.log(this);
return () => {
return this.apply(obj, arguments);
};
}
MyObj1 = function () {
this.myName = 'myObj1';
}
MyObj1.prototype.who = function () {
console.log(this.myName);
}
myObj2 = {
myName: 'myObj2'
}
myObj1 = new MyObj1();
myObj1.who();
who2 = myObj1.who.bind(myObj2);
who2();
produced the following output:
myObj1
ƒ () {
console.log(this.myName);
}
myObj2
is who2 = myObj1.who.bind(myObj2); treat .who as an object and bind this to it?
looks like but still confusing to me
var Person = {
name: "jana",
getName: function(callBack) {
callBack();
console.log("** "+this.name);
}
}
var anotherPerson = { name: "prabu"}
I have 2 objects. I need "anotherPerson" to be bound with the Person object. Also, I want to send parameter as a function.
I have tried below methods, but its not working
Person.getName.apply(anotherPerson, function(){})
Person.getName.apply(anotherPerson)(function(){})
Use call to pass an arbitrary number of arguments to your function, or apply to pass an array of arguments:
var Person = {
name: "jana",
getName: function(callBack) {
callBack();
console.log("** " + this.name);
}
}
var anotherPerson = {
name: "prabu"
}
Person.getName.call(anotherPerson, function () {})
Person.getName.apply(anotherPerson, [function () {}])
Have you tried Object.assign ? Like so
var Person = {
name: "jana",
getName: function(callBack) {
callBack();
console.log("** " + this.name);
}
}
var anotherPerson = {
name: "prabu"
}
Object.assign(Person, anotherPerson).getName(alert)
You can use arrow function and return the name parameter to assign value to getName.
var Person = {
name: "jana",
getName: (obj) =>obj.name
}
var anotherPerson = {
name: "prabu"
}
Person.getName(anotherPerson);
console.log(Person);
I have problem with create Object instance without reference.
I researched and found many people suggest using jQuery.extend to create object without reference.
Refer:
What is the most efficient way to deep clone an object in JavaScript?
But it not success in my case.
Here is my code
JSBin
var MyModel = (function() {
MyModel = function() {};
var myModelObj = {
prop1: null,
prop2: {
sub1: null,
sub2: null
}
};
MyModel.prototype = {
getProp1: function() {
return myModelObj.prop1;
},
getSub1: function() {
return myModelObj.prop2.sub1;
},
getSub2: function() {
return myModelObj.prop2.sub2;
},
setProp1: function(val) {
myModelObj.prop1 = val;
},
setSub1: function(val) {
myModelObj.prop2.sub1 = val;
},
setSub2: function(val) {
myModelObj.prop2.sub2 = val;
},
getObj: function() {
return $.extend({}, myModelObj);
},
setObj: function(json_obj) {
myModelObj.prop1 = json_obj.prop1;
myModelObj.prop2.sub1 = json_obj.prop2.sub1;
myModelObj.prop2.sub2 = json_obj.prop2.sub2;
},
setParam: function(prop1, sub1, sub2) {
myModelObj.prop1 = prop1;
myModelObj.prop2.sub1 = sub1;
myModelObj.prop2.sub2 = sub2;
}
};
return MyModel;
}());
var model1 = new MyModel();
model1.setParam('prop1', 'sub1', 'sub2');
var model2 = new MyModel();
model2.setParam('clone-prop1', 'clone-sub1', 'clone-sub2');
console.log("object 1");
console.log(model1.getObj());
console.log("object 2");
console.log(model2.getObj());
My expected result is
model1 = {
prop1: 'prop1',
prop2: {
sub1: 'sub1',
sub2: 'sub2'
}
}
model2 = {
prop1: 'clone-prop1',
prop2: {
sub1: 'clone-sub1',
sub2: 'clone-sub2'
}
}
But actually, model1 and model2 have same data of model2.
Can someone point me out where i made mistake?
=== Update ===
#arcyqwerty's solution help me solved create object without reference.
var MyModel = function() {
this.prop1 = null;
this.prop2 = {
sub1: null,
sub2: null
};
};
MyModel.prototype = {
getProp1: function() {
return this.prop1;
},
getSub1: function() {
return this.prop2.sub1;
},
getSub2: function() {
return this.prop2.sub2;
},
setProp1: function(val) {
this.prop1 = val;
},
setSub1: function(val) {
this.prop2.sub1 = val;
},
setSub2: function(val) {
this.prop2.sub2 = val;
},
getObj: function() {
return $.extend({}, this);
},
setObj: function(json_obj) {
this.prop1 = json_obj.prop1;
this.prop2.sub1 = json_obj.prop2.sub1;
this.prop2.sub2 = json_obj.prop2.sub2;
},
setParam: function(prop1, sub1, sub2) {
this.prop1 = prop1;
this.prop2.sub1 = sub1;
this.prop2.sub2 = sub2;
}
};
var model1 = new MyModel();
model1.setParam('prop1', 'sub1', 'sub2');
var model2 = new MyModel();
model2.setParam('clone-prop1', 'clone-sub1', 'clone-sub2');
console.log("object 1");
console.log(model1.getObj());
console.log("object 2");
console.log(model2.getObj());
But I also want use encapsulation feature in OOP. It means, we only get value object, property through get function. Is it possible on Javascript?
It explain why i have an object inside Model (but it reference on same object)
Thank you very much!
Try this
var MyModel = function() {
this.prop1 = null;
this.prop2 = {
sub1: null,
sub2: null
};
};
MyModel.prototype = {
getProp1: function() {
return this.prop1;
},
getSub1: function() {
return this.prop2.sub1;
},
getSub2: function() {
return this.prop2.sub2;
},
setProp1: function(val) {
this.prop1 = val;
},
setSub1: function(val) {
this.prop2.sub1 = val;
},
setSub2: function(val) {
this.prop2.sub2 = val;
},
getObj: function() {
return $.extend({}, this);
},
setObj: function(json_obj) {
this.prop1 = json_obj.prop1;
this.prop2.sub1 = json_obj.prop2.sub1;
this.prop2.sub2 = json_obj.prop2.sub2;
},
setParam: function(prop1, sub1, sub2) {
this.prop1 = prop1;
this.prop2.sub1 = sub1;
this.prop2.sub2 = sub2;
}
};
var model1 = new MyModel();
model1.setParam('prop1', 'sub1', 'sub2');
var model2 = new MyModel();
model2.setParam('clone-prop1', 'clone-sub1', 'clone-sub2');
console.log("object 1");
console.log(model1.getObj());
console.log("object 2");
console.log(model2.getObj());
The problem with your original constructor is that instances of MyModel, although different objects created with the new keyword, all share the same myModelObj (which is only ever created once). Using this solution, new fields are created each time you craete a new MyModel.
This is similar to having MyModel = function() { this.myModelObj = {...}; } and accessing fields using this.myModelObj.prop but at that point, myModelObj is a bit redundant as you can just set the properties on this directly.
Also, using this solution, you can use model1.prop directly without having to say model1.getObj().prop (although that works too)
--
Note: it's also a little strange for me to see
var ClassName = (function() {
ClassName = function() { ...; };
ClassName.prototype = { ... };
return ClassName;
})();
Is there a reason you're doing that instead of
var ClassName = function() { ... };
ClassName.prototype = { ... };
?
I suppose it makes sense in the original code if you didn't want to pollute the namespace with myModelObj, but it seems unnecessary otherwise.
--
Edit: encapsulation
If you require an object's properties to be set through getters/setters, you could try something like this:
var MyModel = function() {
var privateObject = {
prop1: null,
prop2: {
sub1: null,
sub2: null
}
};
Object.defineProperty(this, 'prop1', {
get: function() {
console.log('Getting prop1 through getter');
return privateObject.prop1;
},
set: function(value) {
console.log('Setting prop1 through setter');
privateObject.prop1 = value;
}
});
};
The downside is that you won't be able to share getter/setter functions using the prototype chain, meaning you'll have a lot of function objects hanging around. For a small number of instances, this is probably fine (performance-wise). It will also affect inheritance, if your class has subclasses.
If you're on a platform without defineProperty, you can also replicate this by keeping the var privateObject in the constructor and using this.getProp1 = function() { return privateObject.prop1; } in the constructor instead of on the prototype. The net effect is similar to using defineProperty.
--
Edit: or using getter/setter syntax
Note: the returned object is not an instanceof F.
function F() {
var fields = { prop: null };
return {
get prop() {
console.log("getter");
return fields.prop;
},
set prop(value) {
console.log("setter");
fields.prop = value;
}
};
}
f = new F
f.prop = 123
f.prop
This variant of arcyqwerty's answer demonstrates a much deeper encapsulation of your data. The trade-off is that each instance gets its own copy of the methods, rather than sharing them at a "class" level:
var MyModel = function() {
var prop1 = null;
var prop2 = {
sub1: null,
sub2: null
};
this.getProp1 = function() {
return prop1;
};
this.getSub1 = function() {
return prop2.sub1;
};
this.getSub2 = function() {
return prop2.sub2;
};
this.setProp1 = function(val) {
prop1 = val;
};
this.setSub1 = function(val) {
prop2.sub1 = val;
};
this.setSub2 = function(val) {
prop2.sub2 = val;
};
this.getObj = function() {
return {
prop1: prop1,
prop2: {
sub1: prop2.sub1,
sub2: prop2.sub2
}
};
};
this.setObj = function(json_obj) {
prop1 = json_obj.prop1;
prop2.sub1 = json_obj.prop2.sub1;
prop2.sub2 = json_obj.prop2.sub2;
};
this.setParam = function(_prop1, _sub1, _sub2) {
prop1 = _prop1;
prop2.sub1 = _sub1;
prop2.sub2 = _sub2;
};
};
You said,
But I wonder how we protect properties on Javascript?
I think that's the wrong question. JS is a different language, with different concerns than, say, Java or Ruby. It is at least as much a functional language as an OO one. You probably should not try to act as though you're working in Java when you're doing JS, but learn its folkways instead.
I'd like to create a Javascript object that can save and load its state (to local storage).
This is the basic pattern I'm using:
var obj = function () {
// private members
//
return {
// public members
load: function () {
this.state = JSON.parse(localStorage.getItem('obj'));
if (this.state === null) {
this.state = {
name: 'foo'
};
}
},
save: function () {
localStorage.setItem('obj', JSON.stringify(this.state));
}
};
}();
// load state
obj.load();
console.log(obj.state.name);
// save state
obj.state.name = 'bar';
obj.save();
But there's one thing that annoys me about this pattern: I have to access the object's persistent properties through the 'state' property.
How can I rewrite this so I can use the object in a more natural way, like:
// load state
obj.load();
console.log(obj.name);
// save state
obj.name = 'bar';
obj.save();
This is a very simple 'state', but the solution has to work for a complex state object with nested objects, arrays etc., so simply adding a 'name' property to my object is not what I'm after.
If you don't care which properties get loaded/saved then you can simply copy all from state into self. For example, after reading into var state (instead of this.state since you don't want state to be a part of this anymore): for(x in state) this[x] = state[x];
similarly, you'd save out: var state = {}; for(x in this) state[x] = this[x]
However, if you want to have a pre-defined list, then I'd recommend: var fields = ['name', 'zip', 'age'];
And then use for(x in fields) this[x] = state[x] to load and for(x in fields) state[x] = this[x]; to save.
Sorry it's a bit pieced together, but I hope you can follow what I mean :)
EDIT: Added full example per OPs request.
An example of a full solution using this technique is as follows:
var obj = function () {
// private members
//
return {
// public members
load: function () {
var state = JSON.parse(localStorage.getItem('obj'));
if(state == null) state = { name: 'foo' };
for(x in state) this[x] = state[x];
},
save: function ()
{
var state = {};
// check if it's a function. This version taken from underscorejs
var isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
for(x in this)
{
if(isFunction(this[x])) continue; // skip functions
state[x] = this[x];
}
localStorage.setItem('obj', JSON.stringify(state));
}
};
};
You can also accomplish a direct save when a property changes,
by using ES5 getters/setters or by using Watch.js
Watch.js example:
var obj = (function () {
// private members
//
var self = {
// Some properties
name: '',
otherName: '',
// Try to load state or use "foo state"
state: JSON.parse(localStorage.getItem('obj')) || {
name: 'foo'
},
save: function () {
localStorage.setItem('obj', JSON.stringify(this.state));
}
};
// Watch the object and save it to local storage, when a property changes
// (Of course, you don't need to call the save method here...)
watch(self, function(property, value) {
console.log('saving state!');
self.state[property] = value;
self.save();
});
return self;
}());
// Update some properties and see that it is saved to local storage.
obj.name = "Some name";
obj.otherName = "Some other name";
console.log(JSON.parse(localStorage.getItem('obj')));
Example on JsFiddle.
You could make the state internal and surface getters and setters:
var obj = function () {
// private members
var state = {};
return {
// public members
load: function () {
var loadedState = JSON.parse(localStorage.getItem('obj'));
if (loadedState === null) {
state = {
name: 'foo'
};
} else {
state = loadedState;
}
},
save: function () {
localStorage.setItem('obj', JSON.stringify(state));
},
getState: function (key) {
return state[key];
},
setState: function (key, value) {
state[key] = value;
}
};
};
Using jQuery's extend():
var obj = (function () {
return {
load: function () {
var stored = localStorage.getItem("obj");
var state = stored ? JSON.parse(stored) : {
name: 'foo'
};
$.extend(this, state);
},
save: function () {
localStorage.setItem("obj", JSON.stringify(this));
}
};
})();
// load state
obj.load();
console.log(obj);
// save state
obj.name = 'bar';
obj.save();
jsfiddle
All credit to pimvdb.