Javascript pass changing object - javascript

I don't know if it's even possible but we made a statemachine in Javascript.
We have the variable
currentState = stateA
I'd like to pass the currentState as a parameter into an other object, that calls it's methods.
The state changes, so we have
currentState = stateB
The object that uses the currentState call's the stateA method, not the stateB
Is it possible to let it change with it? (pass by reference???)

Not possible. But you can get around it easily. For example:
var StateMachine = (function() {
var _state= null;
return {
setState: function(state) {
_state = state;
},
getState: function() {
return _state;
}
}
})();
var stateA = {
hello: function() {
alert("state A");
}
};
var stateB = {
hello: function() {
alert("state B");
}
}
setState(stateA);
getState().hello(); // prints "state A";
setState(stateB);
getState().hello(); // prints "state B";
This way you make sure the state is only changed via the getter/setter functions.

You can change it if you wrap it in another object. Just as a very rough draft to get you started, you can try this sample:
var StateManager = { currentState: 'stateA' };
function doStuff(sm) {
console.log(sm.currentState); // stateA
changeState(sm);
console.log(sm.currentState); // stateB
}
function changeState(sm) {
sm.currentState = 'stateB';
}
doStuff(StateManager);
Just for the sake of it, here is an idea of what happens:
var o = {a:1}; // o points to an object
f(o); // the pointer is passed to the function
function f(obj) { // obj points to the object above
obj.a = 2; // actual object changed
obj = null; // obj no longer points to that object, but the object remains
}
console.log(o); // o still points to the object

I would say it's possible in some extent.
It all depends on browser support of Ecma script 5.
Have a look at the Object.defineProperty in spec. There you can define get and set methods for your property.
For a more compatible way of doing this use a closure where you define a private variable that you later access with your own defined getState and setState methods.

Related

JS defineProperty setter doesn't triggered

Q1: Can someone explain how to trigger setter in defineProperty, using it via function by this way?
Q2: How to get last key in setter?
fiddle is here
function test(root) {
Object.defineProperty(this, 'subtree', {
get: function() {
console.log("get");
return root.subtree;
},
set: function(value) { //doesn't triggered
console.log("set");
root.subtree = value;
}
});
}
var demo = new test({
subtree: {
state: null,
test: 1
}
});
console.log("START", demo.subtree);
demo.subtree.state = 13; // doesn't triggered setter, but change object
console.log("END", demo.subtree);
To make it simpler, this code
let variable = null;
let obj = {
set variable(value) {
variable = value;
}
get variable() {
return variable;
}
};
obj.variable = {a: 5};
console.log(obj.variable);
does exactly the same thing as this one
let variable = null;
let obj = {
setVariable(value) {
variable = value;
}
getVariable() {
return variable;
}
};
obj.setVariable({a: 5}); // equivalent to obj.variable = {a: 5}
console.log(obj.getVariable()); // equivalent to obj.variable
but the latter clearly shows what's going on.
We want to access a and set it to some value
console.log(obj.getVariable().a); // get a
obj.getVariable().a = 6; // set a!
Notice that we don't call setVariable to set a's value!!! This is exactly what happens in your code. You get subtree and set state to 13. To call setter, you do the following
obj.setVariable({a: 6});
obj.variable = {a: 6}; // getter/setter example
demo.subtree = {state: 13}; // your code
This and this (linked by you) present how scopes and capturing work, so you should get your hands on some book that covers all those things (or browse SO, there are (probably) plenty of questions about that).

javascript class inherit from Function class

I like that in javascript, I can create a function, and then add further methods and attributes to that function
myInstance = function() {return 5}
myInstance.attr = 10
I would like to create a class to generate these objects. I assume I have to inherit from the Function base class.
In other words, I would like to:
var myInstance = new myFunctionClass()
var x = myInstance()
// x == 5
But I don't know how to create the myFunctionClass. I have tried the following, but it does not work:
var myFunctionClass = function() {Function.call(this, "return 5")}
myFunctionClass.prototype = new Function()
myInstance = new myFunctionClass()
myInstance()
// I would hope this would return 5, but instead I get
// TypeError: Property 'myInstance' of object #<Object> is not a function
I also tried the more complicated (and more proper?) inheritance method found here: How to "properly" create a custom object in JavaScript?, with no more luck. I have also tried using the util.inherits(myFunctionClass, Function) found in node.js. Still no luck
I have exhausted Google, and therefore feel that I must be missing something fundamental or obvious. Help would be greatly appreciated.
Your trying to inherit from Function. This is a right pain to do. I suggest you do the following instead
Live Example
var Proto = Object.create(Function.prototype);
Object.extend(Proto, {
constructor: function (d) {
console.log("construct, argument : ", d);
this.d = d;
// this is your constructor logic
},
call: function () {
console.log("call", this.d);
// this get's called when you invoke the "function" that is the instance
return "from call";
},
method: function () {
console.log("method");
// some method
return "return from method";
},
// some attr
attr: 42
});
You want to create a prototype object that forms the basis of your "class". It has your generic methods/attributes. It also has a constructor that gets invoked on object construction and a call method that gets invoked when you call the function
var functionFactory = function (proto) {
return function () {
var f = function () {
return f.call.apply(f, arguments);
};
Object.keys(proto).forEach(function (key) {
f[key] = proto[key];
});
f.constructor.apply(f, arguments);
return f;
}
}
A function factory takes a prototype object and returns a factory for it. The returned function when called will give you a new function object that "inherits" from your prototype object.
var protoFactory = functionFactory(proto);
var instance = protoFactory();
Here you create your factory and then create your instance.
However this isn't proper prototypical OO. we are just shallow copying properties of a prototype into a new object. So changes to the prototype will not reflect back to the original object.
If you want real prototypical OO then you need to use a hack.
var f = function () {
// your logic here
};
f.__proto__ = Proto;
Notice how we use the non-standard deprecated .__proto__ and we are mutating the value of [[Prototype]] at run-time which is considered evil.
JS does not allow a constructor to return a function, even though functions are objects. So you cant have an instantiation of a prototype that is itself executable. (Am I right in this? please correct if I'm not, it's an interesting question).
Though you could do a factory function:
var makeCoolFunc = function() {
var f = function() { return 5 };
f.a = 123;
f.b = 'hell yes!'
return f;
};
var func = makeCoolFunc();
var x = func();
You can extend Function and pass the wanted function body as String to the super constructor. The context of the function can be accessed with arguments.callee.
Example for an observable Attribute class:
export default class Attribute extends Function {
constructor(defaultValue){
super("value", "return arguments.callee.apply(arguments);");
this.value = defaultValue;
this.defaultValue = defaultValue;
this.changeListeners = [];
}
apply([value]){
if(value!==undefined){
if(value!==this.value){
var oldValue = this.value;
this.value=value;
this.changeListeners.every((changeListener)=>changeListener(oldValue, value));
}
}
return this.value;
}
clear(){
this.value=undefined;
}
reset(){
this.value=this.defaultValue;
}
addChangeListener(listener){
this.changeListeners.push(listener);
}
removeChangeListener(listener){
this.changeListeners.remove(listener);
}
clearChangeListeners(){
this.changeListeners = [];
}
}
Example usage:
import Attribute from './attribute.js';
var name= new Attribute();
name('foo'); //set value of name to 'foo'
name.addChangeListener((oldValue, newValue)=>{
alert('value changed from ' +oldValue+ ' to ' +newValue);
});
alert(name()); //show value of name: 'foo'
name('baa'); //set value of name to new value 'baa' and trigger change listener

Trying to get an object to identify its parent object without passing the parent into the child's instance

I'm having troubles finding detailed information on this issue.
I would like to instantiate Bar() within Foo() without having to pass a pointer to Foo(). Or some way for Bar() to know it's a child of Foo(). Is this possible? Or am I already using a sufficient method?
Basically, I'm trying to avoid a call like:
var bar1 = new Bar(this,someValue);
Below I have a rough example of the method I'm currently using.
function Bar(p,val) {
var par = p,
value = val;
this.__defineGetter__("value", function() {
return par.dun.value + value;
});
}
function Dun(val) {
var value = val;
this.__defineGetter__("value", function() {
return value;
});
}
function Foo() {
var dun = new Dun(15);
var bar1 = new Bar(this, 10);
var bar2 = new Bar(this, 20);
this.__defineGetter__("dun", function() {
return dun;
});
this.__defineGetter__("bar1", function() {
return bar1;
});
this.__defineGetter__("bar2", function() {
return bar2;
});
}
var myFoo = new Foo();
myFoo.bar1.value;
Thanks.
No this is not possible, since there is no built in parent/child logic in JavaScript. They are just references to objects.
Update
oh sorry, I think I misunderstood your question. I´ve asked the same question some time ago:
here. What you are trying to do, is to get the object that is "this" in the function that called the current function.
The answer is: you can´t do it...
But you could do it using the scope:
function Dun(val) {
var value = val;
this.__defineGetter__("value", function() {
return value;
});
}
function Foo() {
var dun = new Dun(15);
var bar1 = new Bar(10);
var bar2 = new Bar(20);
this.__defineGetter__("dun", function() {
return dun;
});
this.__defineGetter__("bar1", function() {
return bar1;
});
this.__defineGetter__("bar2", function() {
return bar2;
});
function Bar(val) {
this.__defineGetter__("value", function() {
return dun.value + val;
});
}
}
var myFoo = new Foo();
myFoo.bar1.value;
PS: Not related to your question, but nice to know:
since
function(val){}
is the same as
function(){
var val = arguments[0];
}
you don`t have to create a new var and pass the arguments value to it. You can use the argument variable directly.
There is no way to automatically know the this pointer of the caller of a new. So, if you want to know what that this value is without passing it as part of the constructor, then you'd have to set some semi-global state that contains the appropriate information. You could do so like this:
function Bar(val) {
var par = Bar.parent(),
value = val;
this.__defineGetter__("value", function() {
return par.dun.value + value;
});
}
// global methods and state on the Bar function
Bar.createContext = [];
Bar.push = function(o) {Bar.createContext.push(o);}
Bar.pop = function() {Bar.createContext.pop();}
Bar.parent = function() {return(Bar.createContext[Bar.createContext.length - 1]);}
function Dun(val) {
var value = val;
this.__defineGetter__("value", function() {
return value;
});
}
function Foo() {
Bar.push(this); // set global state
var dun = new Dun(15);
var bar1 = new Bar(10); // don't need to pass "this" since it's in the global state
var bar2 = new Bar(20);
this.__defineGetter__("dun", function() {
return dun;
});
this.__defineGetter__("bar1", function() {
return bar1;
});
this.__defineGetter__("bar2", function() {
return bar2;
});
Bar.pop(); // restore global state
}
var myFoo = new Foo();
myFoo.bar1.value;
And, you can see it work here: http://jsfiddle.net/jfriend00/wMgBL/
You need to give the child object one of the following:
A direct pointer from one object to another, as in your example code.
Unique information about the parent object, such that it can determine what that parent is indirectly through other means.
For example, you could store all instances of Foo in a global registry object (either an object literal or array), which the child bar object could search through. It would be looking for the object that has a child bar equal to itself.1 In this way, the fact that it is a child of Foo is the unique identifier. Unless, of course, one bar can be shared across multiple foos. Then you're hosed. :)
1: The downside to this is that you're storing every instance of Foo ever created, which means they'll never be garbage collected: you'll be leaking memory, which could be bad if your environment sticks around for a while (e.g. a node.js app).

Encapsulation in javascript

I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this?
Here my last non-working code:
SomeClass = function(id) {
this._id = id;
}
(function() {
function intFun() {
return this._id;
}
SomeClass.prototype.extFun = function() {
return incFun();
}
})();
This is my usual approach:
MyClass = function(x, y, z) {
// This is the constructor. When you use it with "new MyClass(),"
// then "this" refers to the new object being constructed. So you can
// assign member variables to it.
this.x = x;
...
};
MyClass.prototype = {
doSomething: function() {
// Here we can use the member variable that
// we created in the constructor.
return this.x;
},
somethingElse: function(a) {
}
};
var myObj = new MyClass(1,2,3);
alert(myObj.doSomething()); // this will return the object's "x" member
alert(myObj.x); // this will do the same, by accessing the member directly
Normally the "this" keyword, when used in one of the object's methods, will refer to the object itself. When you use it in the constructor, it will refer to the new object that's being created. So in the above example, both alert statements will display "1".
An exception to this rule is when you pass one of your member functions somewhere else, and then call it. For example,
myDiv.onclick = myObj.doSomething;
In this case, JavaScript ignores the fact that "doSomething" belongs to "myObj". As a result, the "this" inside doSomething will point to another object, so the method won't work as expected. To get around this, you need to specify the object to which "this" should refer. You can do so with JavaScript's "call" function:
myDiv.onclick = function() {
myObj.doSomething.call(myObj);
}
It's weird, but you'll get used to it eventually. The bottom line is that, when passing around methods, you also need to pass around the object that they should be called on.
I usually don't worry too much about hiding the internals, although I do prefix them with underscores to mark them as not intended to be used outside the "class". Normally what I will do is:
var MyClass = function() {};
MyClass.prototype = {
_someVar : null,
_otherVar : null,
initialize: function( optionHash ) {
_someVar = optionsHash["varValue"];
_otherVar = optionsHash["otherValue"];
},
method: function( arg ) {
return _someVar + arg;
},
};
And use it as so...
var myClass = new MyClass( { varValue: -1, otherValue: 10 } );
var foo = myClass.method(6);
All vars are private:
SomeClass = function (id) {
var THIS = this; // unambiguous reference
THIS._id = id;
var intFun = function () { // private
return THIS._id;
}
this.extFun = function () { // public
return intFun();
}
}
Use THIS within private methods since this won't equal what you might expect.
From http://learn.jquery.com/code-organization/concepts/#the-module-pattern:
// The module pattern
var feature = (function() {
// private variables and functions
var privateThing = "secret";
var publicThing = "not secret";
var changePrivateThing = function() {
privateThing = "super secret";
};
var sayPrivateThing = function() {
console.log( privateThing );
changePrivateThing();
};
// public API
return {
publicThing: publicThing,
sayPrivateThing: sayPrivateThing
};
})();
feature.publicThing; // "not secret"
// logs "secret" and changes the value of privateThing
feature.sayPrivateThing();
So using returning an object that aliases its "methods" could be another way to do it.
I've read from http://www.amazon.com/Programming-Oracle-Press-Poornachandra-Sarang-ebook/dp/B0079GI6CW that it is always good practice to use getters and setters rather that accessing the variable directly from outside the object, so that would eliminate the need of returning variables by reference.
BTW you could just use this.variable to reference/declare a public variable and var variable to declare a private variable.
I know this is a late answer, but I hope it helps anyone who reads it in the future.

Javascript function (type) to store & use data

I really never used a javascript function type or class before, I understand Java and Python, but not javascript. So, I build a class like this:
function FormStore (type) {
this.setup = () =>{
this.store = {};
this.ERR_LINE_PREFIX = '#err_';
this.NO_DISPLAY_CLASS = 'no-display';
this.settings = {
'myID':{'hide':false},
}
}
this.checkVal= () => {
var geoArr = ['id_xx','myID', (...)];
var id;
$.each( geoArr, function(val) {
id = geoArr[val];
console.log(this.store) //-> returns undefined, below line is error
if (!(this.store[id])) {
return false;
}
});
};
var FS = new FormStore();
FS.setup();
The store is filled by components on document.ready. There is a function that looks up if the aligned components (glyph, label, input) have some classes or values and for the specific component fills a dict: {label:false,glyph:false, input:false}. However, for some reason it doesn't matter. Even if I enter some values in to the store right away (in setup) or create them on the fly, in checkVal the store doesn't exist, it's undefined.
Please, anybody, what am I not understanding about javascript type and classes here? I am googling this a lot and trying to find good resources but, "javascipt variable class" (or type) just yields a lot of DOM manipulation.
edit
There is a context problem in checkVal, you are using a non-arrow (and not explicitly bound) callback function and trying to access this inside of it. Change that to an arrow function as well, and the parent context (this) will be preserved:
$.each( geoArr, (val) => {
id = geoArr[val];
console.log(this.store)
if (!(this.store[id])) {
return false;
}
});
And while you are at changing that section, it's not going to work. You will not get access to $.each's return value. You should rely on native array APIs for this task and use Array.every to determine if all geoArr items are in the store (assuming that's your goal):
// returns false if not all geoArr items are in the store
geoArr.every(id => this.store[id])
original
I don't see you calling checkVal() anywhere, but based on the error you are getting it is called prior to setup() (since setup initializes the store). You could solve that problem straight away by moving this.store = {} out of setup (right at the top), e.g.:
function FormStore(type) {
this.store = {};
...
Having said that, I would suggest either defining your methods on the prototype, or utilizing ES6 classes. Here is a simplified version of both:
ES5 class
function FormStore(type) {
// make sure user didn't forget new keyword
if (this === window) {
throw new Error('FormStore must be called with "new" keyword')
}
// initialize state, this is the constructor
this.type = type;
this.store = {};
// any other state the class manages
}
FormStore.prototype = {
setup: function() {
// do setup stuff
// "this" points to instance
console.log('setup', this.type)
},
checkVal: function() {
}
}
var formStore = new FormStore('foo')
console.log(formStore.store) // <-- not undefined
formStore.setup()
ES6 Class
class FormStore {
constructor(type) {
this.type = type;
this.store = {};
}
setup() {
console.log('setup', this.type)
}
checkVal() {
}
}
const formStore = new FormStore('bar')
console.log(formStore.store) // <-- not undefined
formStore.setup()
It has to do with scoping. Your $.each in checkVal has a normal function. Inside the function the scope if this is different. If you want to keep the original scope you could use a fat arrow function like you do when defining the methods.
this.checkVal= () => {
var geoArr = ['id_xx','myID', (...)];
var id;
$.each( geoArr, val => {
id = geoArr[val];
console.log(this.store) //-> returns undefined, below line is error
if (!(this.store[id])) {
return false;
}
});
}
When you run your original code and place a breakpoint on the line with console.log you can see in the inspector that this is set to the Window object and no longer points to your FormStore.
function FormStore () {
this.setup = function(){
this.store = {};
this.ERR_LINE_PREFIX = '#err_';
this.NO_DISPLAY_CLASS = 'no-display';
this.settings = {
'myID':{'hide':false},
}
}
this.checkVal= function(){
var geoArr = ['id_xx','myID'];
var id;
$.each( geoArr, function(val) {
id = geoArr[val];
console.log(this.store) //-> returns undefined, below line is error
if (!(this.store[id])) {
return false;
}
});
}
};
var FS = new FormStore();
FS.setup();
Works absolutely fine, the code you provided had a missing bracket and you were using some broken es6 syntax

Categories

Resources