I have got some JS "objects" I'm using for some complexe stuff. So the following code is reduced to the needed minimal informations:
function AttributeWrapper(model) {
var self = this;
var attributeModel = model;
self.labelPrimitive = null;
self.mandatorySignPrimitive = null;
self.documentationPrimitive = null;
self.valuePrimitive = null;
self.isHidden = function() {
return false;
}
}
function Primitive(model, wrapper) {
var self = this;
var groupingObject = wrapper;
self.model = model;
self.layoutCell = null;
self.render = function() {
if (self.isHidden()) {
return;
}
self.layoutCell.getDomElement().innerHTML = self.model.id || "TODO";
}
self.isHidden = function() {
return groupingObject.isHidden();
}
}
This objects are used mainly like this:
function AnOtherObject {
var self = this;
self.anyFunction = function() {
var wrapper = new AttributeWrapper(model);
var primitive = new Primitive(anOtherKindOfModel, wrapper);
var isHidden = primitive.isHidden();
}
}
For any reason the first call works fine. So the function in the Primitive "class" is called and the scope is correct (variables are set as expected). Also the call by the Primitive class of its contained object (instance of AttributeWrapper) works, but there the context is messed up. I would expect that I can access the instance variables like attributeModel in the "isHidden" function but they do not exist anymore. Also "self" is not the instance but something else (looking like the global "document" or "window" instance), but "this" revers to the instance...
Is there anything i did wrong at the declaration of the objects? I do not understand why the call of the first objects works but the sub-object is wired...
Problem seems to be solved...
I'm using visual studio for debugging. The "return false" of the "isHidden" function in AttributeWrapper was written to place a breakpoint and continue writting the code for this function (to see the objects and their fields in the debugger). When the breakpoint was hitted I had the descript problem.
Today I had a look on it with a colleague who had the idea that maybe just the debugger is confused somehow and do not show the correct state.
So i finished the code and started debugging again. Suddenly the state was correct when the breakpoint gets hit.
So it seems the problem realy was a confused debugger and everthing was working correctly. By using something from the context in the function this confusion seems to be solved...
Lesson learned: visual studio maybe isnt the best choice to debug javascript =)
Related
My question is based on the following scenario.
var test = (function(){
var SlideManager = !function(){
this.Sequencer = {
getSequence : function()...
}
return this;
}()
var LayerManager = !function(){
this.Sequencer = {
getSequence : function()...
}
}()
var module = {};
module.foo = function(){}
return module;
})()
As an explanation, the test object has two helper objects in its scope: SlideManager & LayerManager. These two handle different actions for the entities slide && layer. Each entity has its own fixed position in the DOM, position which should be retrieved through the Sequencer helper object.
Please note that every Manager should have its own Sequencer and I would expect that to be true in the provided example.
However it seems that there is a problem with my understanding of js scopes because both Managers have the same Sequencer (The one from Layer Manager).
Should I expect something like this or am I doing something wrong somewhere else in the code.
Thank you!
To expound upon what Scott Hunter said...
Just auto executing the functions (function() {})() Does not give them a new scope. For that you are wanting the "new" keyword.
So:
var SlideManager = function(){
this.Sequencer = {
getSequence : function()...
}
return this;
};
var LayerManager = function(){
this.Sequencer = {
getSequence : function()...
}
};
var slideManagerInstance = new SlideManage();
var layerManagerInstance = new LayerManager();
Might be more what you are looking for... also why are you "!" banging the auto executed functions return before assigning... that will give you a true/false boolean?
this in both Managers isn't local to that function, and thus is the SAME in both, which is why they have the same Sqeuencer.
I am new to this so I'll try to be as detailed as possible.
I am creating a JS class using functions.
function Bandstar(p, id)
{
var numberOfSides, Xcenter, Ycenter;
var canvas;
var circlesInt;
var linesInt;
var lines;
var linesInt2;
var linesMidToEdge;
.....
When it comes to methods, I just declare them like this:
this.IAset = function(a)
{
for (var i =0; i<= this.numberOfSides-1;i++)
{
if (parseInt(a[i]) == a[i])
this.circles[i].value = a[i];
else
return false;
}
this.IArepaint();
return true
}
and that's pretty much it.
The problem now is that, when I am creating a specific method:
this.moveFunc = function(e)
{
var p = e.target;
this.IAmove(p);
};
with the method IAmove being declared as follows:
this.IAmove = function(p)
{
var m = (p.oTop - this.Ycenter ) / (p.oLeft - this.Xcenter);
var linea = m * ( p.left - p.oLeft) + p.oTop;
var ejeX = p.left;
...
}
The compiler just keeps throwing this error:
Uncaught TypeError: Object function (e) { var p = e.target; this.IAmove(p); } has no method 'IAmove'
So, the thing is that I am declaring moveFunc as a function but then when I try to get to use this property, it doesn't actually use the instance of the class above it, (Bandstar), but of itself (and obviously moveFunc doesn't have a method called IAmove, the class on which it is being created is)...
I thought this was just like it worked, but I must not be getting the concept of heritage and class morphology in JS right.
How can I access a method in a class from another method inside that same class? If I just write IAmove(p) it will just say the method IAmove() is undefined (because it isn't, it's part of the Bandstar namespace.
I know it must be something stupid that I'm not seeing. Any suggestions?
The context inside your function may change based on your call. So this could not be the original object.
You should add a private var like:
function Bandstar(p, id)
{
var numberOfSides, Xcenter, Ycenter;
var canvas;
var that = this; // add this line
and use it when you try to call function (or get properties) of original object
this.moveFunc = function(e)
{
var p = e.target;
that.IAmove(p); // change this line
};
for be sure to point to original object.
EDIT: According with comments you can read more infos in Stuart's answer
You probably wants to add these methods to your Bandstar prototype.
function Bandstar(p, id)
{
// ...
}
Bandstar.prototype.IAset = function(a)
{
// ...
}
Bandstar.prototype.moveFunc = function(e)
{
var p = e.target;
this.IAmove(p);
};
This way your methods keep the Bandstar context, and this will remain Bandstar instance reference.
Have a look at Object.prototype reference
Assuming all of those methods are defined in the constructor the syntax is correct. The following fiddle illustrates it working, the code is based on a simplified version of your code...
function Test() {
this.move = function(p) {
document.write("Moved to: " + p);
};
this.another = function(e) {
this.move(e.target);
};
}
var test = new Test();
test.another({target: "The moon"});
The cause of the issues is likely to be one of two three things:
How the method moveFunc is called
When the method moveFunc is called
How the method IAmove is called (it may not be the moveFunc function that is causing that error).
The this keyword will reference the scope of the function which is typically the owner of the method...
var bandstar = new Bandstar(p, id);
bandstar.moveFunc(e); // this should be bandstar
The only reasons that might not be the case is if you are explicitly binding the moveFunc function to another object or a more common situation is that the function is being called without being attached to the owner...
var bandstar = new Bandstar(p, id);
var moveFunc = bandstar.moveFunc(e);
moveFunc(e); // this will now be window
The this keyword will default to window if the owner is detached from it. You can bind the function using.
var bandstar = new Bandstar(p, id);
var moveFunc = bandstar.moveFunc(e);
moveFunc.bind(bandstar);
moveFunc(e); // this will now be bandstar again
In the second issue both methods must be defined in the constructor before the moveFunc function can be called
this.moveFunc = function(e) { ... }
this.moveFunc(e); // Will throw an error that IAmove does not exist in the object
this.IAmove = function(p) { ... }
You can log the this object using console.log(this); to find out what it is.
It looks as though from your error that you are trying to call IAmove on the moveFunc function. For this error to be caused you would need to have called moveFunc with itself as the owner or the bound object... Which is not a particularly likely.
I have a hunch that the error may not actually be related to the this.IAmove(p); call in the moveFunc as assumed. Post the stack trace and we can use that to find where the error occurred.
I want to create modules to structure my NodeJS application, but I'm a little lost, and I haven't found anything (with hours of searching) that is completely definitive on the subject.
Say I'd like to create a "user" module, from which I can create new users in my code using something like:
var newUser = new User();
Ideally, I'd require my module at the top of my code using something like:
var User = require('../lib/user');
This works great. The question is, how should I structure the user module? Is the following the best way?
module.exports = function User() {
var authorized = false;
var username = undefined;
var password = undefined;
var statistics = undefined;
this.authorized = function() {
return authorized;
}
this.username = function() {
return username;
}
this.statistics = function() {
return statistics;
}
}
I'm writing getters and setters for my various module variables, allowing me to hide things I don't want to accidentally access from other code. However, I have done it this way before:
function User() {
this.authStatus = false;
this.email;
this.displayName;
this.inSession;
}
User.prototype.isAuthenticated = function() {
return(this.authStatus && this.email && this.displayName)
}
User.prototype.isInSession = function() {
return(this.inSession && this.isAuthenticated());
}
exports.User = User;
This works too, with one caveat; I haven't found a way to access the user properties from within closures. If my understanding is correct, with the second implementation, I can't. This means if I need to hand a function off to a db library as a callback to edit the user's properties, I can't. That'd look something like:
User.prototype.login = function() {
db.doDbStuff('get user data query', function(_error, _result) {
this.username = _result[0].name; //this code will not work
});
}
The code doesn't work, to my understanding, because the "this" keyword is within the scope of the closure, not the User. Even if the code were to be placed within the User function:
function User() {
this.login = function() { //you know
It wouldn't work.
I guess my question is, what's the best solution to this problem? Is it the method I presented in the first code block? That seems rather cumbersome and messy and prone to variable collision. I'm scared.
Thanks in advance!
I typically go with the second approach, attaching functions to the prototypes.
The issue you're having with variables "not being available in closures" has nothing to do with prototypes. You'd have that same issue either way you structure it.
It's to do with javascript's oft-confusing dynamic this:
http://robotlolita.me/2011/10/09/understanding-javascript-oop.html#sec-2-1
Basically, you need to do something like:
User.prototype.login = function() {
var self = this // bind this to self so you have a reference to what `this` was
db.doDbStuff('get user data query', function(_error, _result) {
self.username = _result[0].name; // self refers to the original `this`, so this works.
});
}
You also have the option of using function.bind: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Within the bound function, the value of this will be whatever value you provided to .bind(value):
User.prototype.login = function() {
db.doDbStuff('get user data query', (function(_error, _result) {
this.username = _result[0].name; // bind fixes the original `this`, so this also works.
}).bind(this));
}
Whether you use function.bind or self = this is somewhat of a personal taste question, but we were doing some benchmarks in the freenode#nodejs the other day and discovered bind() is 20 something times slower than var self = this.
As to your original question about how to structure modules, there are so many examples to learn from on github. Simply find your favourite module and inspect how they structure it. I notice that many people seem to prefer factories over exposing constructors directly (e.g. require('module').create() ). Your call.
As a different approach, I am a fan of the following pattern.
module.exports = function User(data) {
//this properly private stuff.
var privateVar;
var username = data.username;
var pass = data.pass; //etc
function privateFunc() {
}
return {
login: function(cb) {
db.doStuff(username, pass, cb);
}
};
};
User.prototype.login = function() {
var _this = this;
db.doDbStuff('get user data query', function(_error, _result) {
_this.username = _result[0].name; //this code will now work
});
}
The 'this' you used was outside its scope, it was the callback 'this'.
I have some js code here link deleted
If you open your js console and you'll run this code snipet
var r = new TempPopupForm("xxx");
r.create();
an error will appear
TypeError: this.init is not a function
this error is saying there is no init method implemented on this object.
But that's not true.As you can see in the code below the init method is declared.
TempPopupForm.prototype = new PopupForm();
TempPopupForm.prototype.constructor = TempPopupForm;
TempPopupForm.superclass = PopupForm.prototype;
function TempPopupForm(name) {
this.init(name);
}
TempPopupForm.prototype.init = function(name) {
TempPopupForm.superclass.init.call(this, name);
};
I guess something is wrong with the inheritance definition,but I can not figure out what it is.
BTW There are some third party dependencies.
EDIT
I was following this article and where the funcs are ordered like I have. The order actually works on the other classes, but not on this one.
http://www.kevlindev.com/tutorials/javascript/inheritance/inheritance10.htm
You need to re-order your functions and instantiation. Since your constructor is using one of its own prototyped method to init, they both need to be above the block where you instantiate the object. JavaScript hoists top-level functions.
Try this -
function TempPopupForm(name) {
this.init(name);
}
TempPopupForm.prototype = new PopupForm();
TempPopupForm.prototype.constructor = TempPopupForm;
TempPopupForm.superclass = PopupForm.prototype;
TempPopupForm.prototype.init = function(name) {
TempPopupForm.superclass.init.call(this, name);
};
var r = new TempPopupForm("xxx");
r.create();
The code below is adapted from this answer
function MessageClass() {
var self = this;
this.clickHander = function(e) { self.someoneClickedMe = true; };
var _private = 0;
this.getPrivate = function() { return _private; };
this.setPrivate = function(val) { _private = val; };
}
ErrorMessageClass.prototype = new MessageClass();
function ErrorMessageClass() {
MessageClass.apply(this, arguments);
}
var errorA = new ErrorMessageClass();
var errorB = new ErrorMessageClass();
errorA.setPrivate('A');
errorB.setPrivate('B');
console.log(errorA.getPrivate());
console.log(errorB.getPrivate());
The original post did not have the MessageClass.apply(this, arguments); since the purpose was to show how inheritance can go wrong in Javascript.
My question is, is saying: ErrorMessageClass.prototype = new MessageClass(); before the ErrorMessageClass constructor has even been declared bad practice? My understanding is that calling undeclared identifiers like that causes a silent declaration to occur, with the result being placed on the global window object, which I understand is bad.
Is this form:
function ErrorMessageClass() {
MessageClass.apply(this, arguments);
}
ErrorMessageClass.prototype = new MessageClass();
considered to be better practice? This link shows the code written as it was originally above, which is why I even tried it. Does this blogger know something I don't (quite likely)?
EDIT
Lots of great info in the answers below, but I did want to highlight this link which really explains things perfectly
Usually, to avoid this confusion, you would just attach the prototype after, but as Adam Rackis pointed out, function declarations are hoisted, like var statements.
However, you should not instantiate the base object as the prototype. If your base object takes arguments, what are you supposed to use? Use an empty "surrogate" constructor
// Used to setup inheritance
function surrogate () {};
function MessageClass() {
var self = this;
this.clickHander = function(e) { self.someoneClickedMe = true; };
var _private = 0;
this.getPrivate = function() { return _private; };
this.setPrivate = function(val) { _private = val; };
}
// The key steps to creating clean inheritance
surrogate.prototype = MessageClass;
// Sets up inheritance without instantiating a base class object
ErrorMessageClass.prototype = new surrogate();
// Fix the constructor property
ErrorMessageClass.prototype.constructor = ErrorMessageClass
function ErrorMessageClass() {
MessageClass.apply(this, arguments);
}
There's much more to be said. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
It works because function declarations are evaluated first. If you tried to move these classes under an object literal "namespace" the first version would fail.
I personally find the second method to be much easier to read - also, don't forget to set the sub-class' prototype.constructor property back to itself. Personally, I use an inherits() method on the Function prototype which wraps up essentially the type of code you're using here.