Module pattern and this - javascript

I am using the module pattern for my JavaScript "classes". Is there any significant downside to declaring a var self outisde of the class I am returning and then setting it to this inside the class constructor so that I don't have to worry about the context switching when I don't want it to. In this small example it's probably unnecessary, this is just an example.
Example:
var Seat = (function() {
var self = null;
function Seat(startX, startY, inputSeatNumber, inputTableNumber) {
self = this;
self.radius = 10;
self.x = startX; self.y = startY;
self.seatNumber = inputSeatNumber;
self.tableNumber = inputTableNumber;
}
Seat.prototype.moveTo = function(newX, newY) {
if(newX >= 0 && newY >= 0) {
self.x = newX; self.y = newY;
}
};
return Seat;
})();
EDIT: example added
var SeatingChartView = (function() {
function SeatingChartView(canvas_id, seatingChartController, seatForm) {
this.stage = new createjs.Stage(canvas_id);
this.controller = seatingChartController;
this.seatForm = seatForm;
this.disableRightClick(canvas_id);
}
SeatingChartView.prototype.render = function() {
this.stage.update();
}
SeatingChartView.prototype.addSeat = function(newSeat) {
var newCircle = new createjs.Shape();
newCircle.graphics.beginFill("black").drawCircle(0, 0, 10);
newCircle.x = newSeat.x;
newCircle.y = newSeat.y;
newCircle.seat = newSeat;
newCircle.on('click', function(event) {
if(event.nativeEvent.button == 2) {
this.seatForm.open(event.currentTarget.seat);
}
});
newCircle.on('pressmove', this.controller.moveSeat)
this.stage.addChild(newCircle);
}
SeatingChartView.prototype.removeSeat = function(seat) {
this.stage.children.forEach(function(child) {
if(child.seat === seat) {
this.stage.removeChild(child);
}
});
}
SeatingChartView.prototype.setBackground = function(imageLocation) {
this.background = new createjs.Bitmap(imageLocation);
window.setTimeout(function() {
this.stage.canvas.width = this.background.image.width;
this.stage.canvas.height = this.background.image.height;
this.stage.addChild(this.background);
this.stage.update();
}.bind(this), 500);
}
SeatingChartView.prototype.disableRightClick = function(canvas_id) {
$(function() {
$('#' + canvas_id).bind('contextmenu', function(e) {
return false;
});
});
}
return SeatingChartView;
})();

In that case every new instance of Seat will share the newest Self object since it is set in the constructor. You should avoid doing this.

A more practical demo example might be something like this, where you want to make sure this is the instance of the class.
function Foo() {
var _this = this;
_this.someItem = {};
_this.go = function() {
doSomethingElse(function(result) {
_this.someItem.something = result; // _this and this are different
});
};
};
function doSomethingElse(callback) {
callback('asdf');
}
var foo = new Foo();
foo.go();
For your example using that pattern, you can define the _this in each method if it would be any benefit (this one wouldn't, but a more complex example might):
Seat.prototype.moveTo = function(newX, newY) {
var _this = this;
if(newX >= 0 && newY >= 0) {
_this.x = newX; _this.y = newY;
}
};

Yes, by doing it this way, all instances of Seat will have the same this, causing problems all over the place. Just remove the var self and use this in all places where you were using self. In the code you've given, there's no point where you will lose reference to this.
(#added example) Now your question makes more sense.
Instead of trying to handle this for all methods at once, you'll have to handle it at each point where you're using a function that has a different this (any function that isn't on the prototype or instance).
If you don't need this inside the callback, I would just use .bind to make the instance this available inside. Note however that .bind isn't supported in some (very)old versions of IE, so you'll either need a polyfil to work for those, or store this in a var.
SeatingChartView.prototype.addSeat = function(newSeat) {
var newCircle = new createjs.Shape();
newCircle.graphics.beginFill("black").drawCircle(0, 0, 10);
newCircle.x = newSeat.x;
newCircle.y = newSeat.y;
newCircle.seat = newSeat;
newCircle.on('click', function(event) {
if(event.nativeEvent.button == 2) {
this.seatForm.open(event.currentTarget.seat);
}
}.bind(this)); // modified here, added `.bind(this)`
newCircle.on('pressmove', this.controller.moveSeat)
this.stage.addChild(newCircle);
}

This would totally negate the purpose of "classing". But in JS it's called prototyping.
Principally you want the base prototype to be "copied" when creating new instances. The base prototype should be shielded from changes when extended.
Suppose you have done what you did, all instances of Seat will have the same properties. Even worst, when creating new "copies" of Seat, all other previously created copies will have their values changed.
Since you want this to maintain reference to Seat, I would recommend using the following pattern:
var Base = {
init: function(arg) {
this.name = arg;
},
getName: function() {
return this.name;
}
}
Base.init('foo');
Base.getName(); // returns 'foo'
Your transformed code:
var Seat = {
init: function(startX, startY, inputSeatNumber, inputTableNumber) {
this.radius = 10;
this.x = startX;
this.y = startY;
this.seatNumber = inputSeatNumber;
this.tableNumber = inputTableNumber;
},
moveTo: function(newX, newY) {
if (newX >= 0 && newY >= 0) {
this.x = newX; this.y = newY;
}
},
setBackground: function(imageLocation) {
var self = this;
this.background = new createjs.Bitmap(imageLocation);
setTimeout(function() {
self.stage.canvas.width = self.background.image.width;
self.stage.canvas.height = self.background.image.height;
self.stage.addChild(self.background);
self.stage.update();
}, 500);
}
}
Extend the prototype:
var vipSeat = Object.create(Seat);
vipSeat.init( //your init values )
You can also not create an init method and simply use Object.create's second argument to assignment initial values to the prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Example:_Using_propertiesObject_argument_with_Object.create

Related

Dartlang class VS JavaScript class

I've the below JS code using JS classes, that multiple rectangles got generated, in different random locations,
the static rectangle start moving upon click, and the moving rectangle is destroyed if clicked.
I want to re-write the same code in Dart language, I did not know what shall I use instead of the JS myRect.prototype in dart, considering that I prefer not to include all the class properties and functions inside the main class { } any idea?
var NS="http://www.w3.org/2000/svg";
var SVG=function(h,w){
var svg=document.createElementNS(NS,"svg");
svg.width=w;
svg.height=h;
return svg;
}
var svg=SVG(1200,1500);
document.body.appendChild(svg);
class myRect {
constructor(x,y,h,w,fill,name) {
this.name=name;
this.SVGObj= document.createElementNS(NS,"rect");
self = this.SVGObj;
self.x.baseVal.value=x;
self.y.baseVal.value=y;
self.width.baseVal.value=w;
self.height.baseVal.value=h;
self.style.fill=fill;
self.addEventListener("click",this,false);
}
}
Object.defineProperty(myRect.prototype, "draw", {
get: function() {
return this.SVGObj;
}
});
myRect.prototype.handleEvent= function(evt){
self = this.SVGObj;
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true)
self.move = setInterval(()=>this.animate(),100);
else{
clearInterval(self.move);
self.parentNode.removeChild(self);
}
break;
default:
break;
}
}
myRect.prototype.step = function(x,y) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().translate(x,y));
}
myRect.prototype.animate = function() {
self = this.SVGObj;
self.transform.baseVal.appendItem(this.step(1,1));
};
for (var i = 0; i < 100; i++) {
var x = Math.random() * 500,
y = Math.random() * 300;
var r= new myRect(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16),'this is my name');
svg.appendChild(r.draw);
}
You can't add methods to a class or object dynamically in Dart. Your options are:
Put them inside the class
Make them functions that take the rectangle as an argument
I would go with (2), just make them functions that accept an instance of your class:
handleEvent(myRect, evt){
// ...
}

Accessing outer scope from inner scope

I have a type that looks a little something like this:
var x = function(){
this.y = function(){
}
this.z = function(){
...
this.A = function(){
CALLING POINT
}
}
}
From calling point, I'm attempting to call function this.y. I don't need to pass any parameters, but when I set some stuff from this.A, I need to call this.y.
Is this possible? I'm OK with passing extra parameters to functions to make it possible.
Is this possible?
Yes, you can assign this reference to another variable and then call function y on it
this.z = function() {
var self = this;
this.A = function() {
self.y();
}
}
Version with bind, basically this adds a new method a to the object.
var X = function () {
this.y = function () {
document.write('y<br>');
}
this.z = function () {
document.write('z<br>');
this.a = function () {
document.write('a<br>');
this.y();
}
}.bind(this);
};
var x = new X;
//x.a(); // does not exist
x.z(); // z
x.a(); // a y
Working example with saved inner this.
var X = function () {
var that = this; // <--
this.y = function () {
document.write('y<br>');
}
this.Z = function () {
document.write('Z<br>');
this.a = function () {
document.write('a<br>');
that.y();
}
}
}
var x = new X,
z = new x.Z; // Z
z.a(); // a y
Instead of function() you can try modern JavaScript or Typescript ()=>. I also like .bind(this).
You cannot because this.y() is not within the scope that this.A() is in. You can if you set this.y() to a global function y:
var y = function() {};
var x = function() {
this.y = y;
this.z = function() {
...
this.A = function() {
this.y(); // will be successful in executing because this.y is set to the y function.
};
}
};

Javascript, get "this" from prototype function own field [duplicate]

This question already has answers here:
prototype: deep scope of "this" to access instance's scope
(5 answers)
Closed 6 years ago.
Suppose I have following code:
var Model = function() {};
Model.prototype.a = function() {//do smth
Model.prototype.a.on = function() {//do smth
var m = new Model();
m.a();
m.a.on();
Now I need reference to specific object m from m.a() and m.a.on() calls.
When calling m.a(), i have this referring to m.
Is it possible to get reference to m from m.a.on() call somehow?
It's a very bad idea to do so, as it leads to very strange behaviour in some cases, but it's possible:
var Model = function(x) { this.x = x };
Object.defineProperty(Model.prototype, 'a', (function() {
var lastSelf;
function get() { return lastSelf.x }
get.on = function () { return lastSelf.x * 2 };
return { get() { lastSelf=this; return get } };
})());
var m = new Model(17);
console.log(m.a(), m.a.on());
Why? I see your answer below, trying to realize what are bad cases.
You can't pass a through the variable.
You must grant access to on immediately after getting property a of the same object:
var Model = function(x) { this.x = x };
Object.defineProperty(Model.prototype, 'a', (function() {
var lastSelf;
function get() { return lastSelf.x }
get.on = function () { return lastSelf.x * 2 };
return { get() { lastSelf=this; return get } };
})());
var m1 = new Model(1), m2 = new Model(3);
console.log(m1.a(), m2.a(), m1.a.on(), m2.a.on()); // 1 3 2 6 - ok
var a1 = m1.a, a2 = m2.a;
console.log(m1.a(), m2.a(), a1.on(), a2.on()); // 1 3 6 6 - ooops!
console.log(m1.a(), m2.a(), m1.a(), a1.on(), a2.on()); // 1 3 1 2 2 - ooops!
And the other solution, but with using __proto__. According to ES6 this solution is valid for browser enviroments and for server enviroments __proto__ have to be replaced by Object.setPrototypeOf. Be sure to check browser support and other warnings.
This solution adds 1 function and 1 object per each instance.
function Model(x) {
this.x = x;
this.a = function () { return Model.prototype.a.call(this, arguments) };
this.a.__proto__ = Object.create(Model.prototype.a);
this.a.this = this;
}
Model.prototype.a = function () { return this.x };
Model.prototype.a.on = function () { return this.this.x * 2 };
var m1 = new Model(1), m2 = new Model(3);
console.log([m1.a(), m2.a(), m1.a.on(), m2.a.on()] == "1,3,2,6");
var a1 = m1.a, a2 = m2.a;
console.log([m1.a(), m2.a(), a1.on(), a2.on()] == "1,3,2,6");
console.log([m1.a(), m2.a(), m1.a(), a1.on(), a2.on()] == "1,3,1,2,6");
You can rebind the 'grandchild' methods manually in the constructor:
bindAll = function(self, obj) {
Object.keys(obj).forEach(function(k) {
if(typeof obj[k] === 'function')
obj[k] = obj[k].bind(self);
});
}
var Model = function() {
bindAll(this, this.a);
this.x = 123;
};
Model.prototype.a = function() {}
Model.prototype.a.on = function() {
console.log(this.x);
}
var m = new Model();
m.a();
m.a.on();
A more memory-savvy way is to use an explicit pointer to the root class and consistently use this.root instead of just this in methods:
var Model = function(x) {
this.x = x;
this.model = this;
this.a = Object.create(this.a);
this.a.model = this;
};
Model.prototype.a = function() {
console.log(this.model.x);
}
Model.prototype.a.on = function() {
console.log(this.model.x);
};
var m1 = new Model(11), m2 = new Model(22);
m1.a.on();
m2.a.on();
m1.a.on();
You can't access directly the parent object from a.on. You have to define some property (e.g. parent) linked to main object before calling a.on:
var Model = function() {};
Model.prototype.a = function() {//do smth
console.log(this.i);
}
Model.prototype.a.on = function() {//do smth
console.log(this.parent.i);
}
var m = new Model();
m.i = 11;
m.a();
m.a.parent = m
m.a.on();

Updating values with a function, returning not working

So I am using a function to update my values, but I can't then get them back. I see values don't get updated, but is there any way of saving them as a reference to the return of the function.
function Amphibia(wheelRadius, finsPerPropeller, propellersSpinDirection, mode) {
this.speed = 0;
this.mode = mode;
var amphibiaWheel = new PropulsionUnits.Wheel(wheelRadius);
var amphibiaPropeller = new PropulsionUnits.Propeller(finsPerPropeller, propellersSpinDirection);
this.changeMode = function () {
if (mode == "land") {
mode = "water";
}
else if(mode == "water") {
mode = "land";
}
return {
mode: mode
}
}
this.accelerate = function() {
if(this.mode == "water"){
this.speed += amphibiaPropeller.acceleration;
}
else if(this.mode == "land"){
this.speed += 4*amphibiaWheel.acceleration;
}
}
this.changePropellerSpinDirection = function() {
amphibiaPropeller.changeSpinDirection();
}
return {
speed: this.speed,
mode: this.mode,
changeMode: this.changeMode,
accelerate: this.accelerate,
changePropellerSpinDirection: this.changePropellerSpinDirection
}
}
So here I am experiencing problems with changing the mode and the changeMode function expression. Mode in it should refer to this.mode and then I should be able to update the value.
mode and this.mode are not the same. In your functions you are checking/setting values on mode and this.mode, separately.
Either should work fine, as long as you're using one or the other, in the same place, the same way.
Edit
var Amphibia = function (wheelRadius, finsPerPropeller, propellersSpinDirection, mode) {
var amphibia = this,
MODES = { LAND : "land", WATER : "water" };
amphibia.getMode = function () { return mode; };
amphibia.setMode = function (val) { mode = val; };
amphibia.changeMode = function () {
amphibia.setMode((mode === MODES.LAND) ? MODES.WATER : MODES.LAND);
};
};
var amphibia = new Amphibia("", "", "", "land");
amphibia.getMode(); // "land"
amphibia.changeMode();
amphibia.getMode(); // "water"
mode is now 100% private, and unique to that instance.
If you don't need it to be, then you can append it to this, if you'd like.
But here's your problem:
var Amphibia = function () {
var amphibia = this,
amphibiaPropeller = new Propeller( );
// mode, getMode, setMode, etc...
amphibia.accelerate = function () {
if (amphibia.getMode() === "water") {
this.speed += amphibiaPropeller.acceleration;
}
};
};
var amphibia = new Amphibia();
var bob = { speed : 0 };
bob.accelerate = amphibia.accelerate;
bob.accelerate();
// if amphibia.mode === "water", bob.speed += amphibiaPropeller.acceleration
bob.speed; // === amphibiaPropeller.acceleration
setTimeout(amphibia.accelerate, 10); // call amphibia.accelerate in ~10ms
// if amphibia.mode === "water", window.speed += amphibiaPropeller.acceleration
window.speed; // === amphibiaPropeller.acceleration
Be consistent in how you refer to things.
Don't mix self and this, unless you intend to get those side-effects...
And unless you have a very, very good reason to do so (like you're building a framework/engine, not the modules/classes of the game/simulation which use the engine; ie: the difference between building jQuery and building something with jQuery), then you should probably avoid doing it.
If you have closure ("private") state that you want to expose to the outside world, all you need is a function that returns that value, and/or one that sets it.
All of a sudden, the differences between self and this and what is which, when, all go away, as long as you are consistent with how you use them, and you know what the value of this is going to be, every time you call the method.
Notice I'm not returning anything...
When I use new, the value of this (amphibia/self) gets returned by default.
If you want to use private values, and return a "Revealing Module" (which is what I typically prefer), then you can simply do this:
var Amphibia = function (mode) {
var getMode = function () { return mode; },
setMode = function (val) { mode = val; },
changeMode = function () {
setMode( mode === "water" ? "land" : "water" );
};
return {
getMode : getMode,
setMode : setMode,
changeMode : changeMode
};
};
var amphibia = new Amphibia("water");
// `new` won't do any harm, but you can also not use it,
// without it saving everything to `window`
amphibia.getMode(); // "water"
amphibia.changeMode();
amphibia.getMode(); // "land"
Or, maybe if you want that to look a little more like a module/component...
return {
mode : { get : getMode, set : setMode, switch : changeMode }
};
var amphibia = Amphibia("land");
amphibia.mode.get(); // "land"
amphibia.mode.switch();
amphibia.mode.get(); // "water"
var bob = { };
bob.switchAmphibiaMode = amphibia.mode.switch;
bob.switchAmphibiaMode();
amphibia.mode.get(); // "land"
setTimeout(amphibia.mode.switch, 10);
setTimeout(function () { console.log(amphibia.mode.get()); }, 20);
// 10ms amphibia.mode.switch();
// 20ms console.log(amphibia.mode.get());
// > "water"
...or whatever other structure you'd like.
You don't need a this at all.
But this is something to be very, very careful with in JavaScript, because the meaning of this changes every time you call a function, and if half of the code uses this and half uses self, you're bound for some surprises.
I managed to find the answer myself! :) So basicly this in the function constructor refers to Amphibia and this in the this.changeMode function expression refers to object window. Therefore we can define a variable self = this; in the constructor, so we can refer to the same thing in the function expression, as in the function. I explained it a bit awful, but here is my fixed code ;)
function Amphibia(wheelRadius, finsPerPropeller, propellersSpinDirection, mode) {
this.speed = 0;
var self = this;
self.mode = mode;
var amphibiaWheel = new PropulsionUnits.Wheel(wheelRadius);
var amphibiaPropeller = new PropulsionUnits.Propeller(finsPerPropeller, propellersSpinDirection);
this.changeMode = function () {
if (self.mode == "land") {
self.mode = "water";
}
else if(self.mode == "water") {
self.mode = "land";
}
}
this.accelerate = function() {
if(self.mode == "water"){
this.speed += amphibiaPropeller.acceleration;
}
else if(self.mode == "land"){
this.speed += 4*amphibiaWheel.acceleration;
}
}
this.changePropellerSpinDirection = function() {
amphibiaPropeller.changeSpinDirection();
}
return {
speed: this.speed,
mode: this.mode,
changeMode: self.changeMode,
accelerate: this.accelerate,
changePropellerSpinDirection: this.changePropellerSpinDirection
}
}

javascript object, self reference problem

I just started using oop in javascript and I ran across some problems trying to acces a method from inside another method.
here's the code I had:
var Game = {
initialize: function () {
if (canvas.isSupported()) {
sprites[0] = new Player();
this.update();
}
},
update: function() {
for (var i = 0; i < sprites.length; i++) {
sprites[i].update();
}
this.draw();
},
draw: function() {
this.clear();
for (var i = 0; i < sprites.length; i++) {
sprites[i].draw();
}
setTimeout(this.update, 10);
},
clear: function() {
canvas.context.clearRect(0, 0, canvas.element.width, canvas.element.height);
}
}
but calling the Game.update() gives an error that the draw method isn't defined.
I couldn't find a real solution for this.
eventually I found this How to call a method inside a javascript object
where the answer seems to be that I need to safe the this reference like:
var _this = this;
but I couldn't get that to work in literal notation, so I changed the code to object constructor (I guess that's how it's called) and added the variable.
I then changed
this.draw();
to
_this.draw();
and it worked.
though the
this.clear();
and the this.update() are still the same, they never seemed to give errors in the first place.
Can anyone explain why this is? and maybe point me to a better solution?
thanks in advance.
update
Here's what it should be:
var Game = function () {
var _this = this;
this.initialize = function () {
if (canvas.isSupported()) {
sprites[0] = new Player();
this.update();
}
}
this.update = function () {
for (var i = 0; i < sprites.length; i++) {
sprites[i].update();
}
this.draw();
}
this.draw = function () {
this.clear();
for (var i = 0; i < sprites.length; i++) {
sprites[i].draw();
}
setTimeout(function () { _this.update(); }, 10);
}
this.clear = function () {
canvas.context.clearRect(0, 0, canvas.element.width, canvas.element.height);
}
}
When you do this:
setTimeout(this.update, 10);
that does correctly pass the reference to your "update" function to the system, but when the browser actually calls the function later, it will have no idea what this is supposed to be. What you can do instead is the following:
var me = this;
setTimeout(function() { me.update(); }, 10);
That will ensure that when "update" is called, it will be called with this set correctly as a reference to your object.
Unlike some other languages, the fact that a function is defined initially as a property of an object does not intrinsically bind the function to that object. In the same way that if you had an object with a propertly that's a simple number:
maxLength: 25,
well the value "25" won't have anything in particular to do with the object; it's just a value. In JavaScript, functions are just values too. Thus it's incumbent upon the programmer to make sure that this will be set to something appropriate whenever a function is called in some "special" way.
You problem is that you use an object literal instead of an instantiated object
Try to do it this way instead:
var Game = function() {
this.initialize = function () {
if (canvas.isSupported()) {
sprites[0] = new Player();
this.update();
}
};
this.update = function() {
for (var i = 0; i < sprites.length; i++) {
sprites[i].update();
}
this.draw();
};
this.draw = function() {
this.clear();
for (var i = 0; i < sprites.length; i++) {
sprites[i].draw();
}
setTimeout(this.update, 10);
};
this.clear = function() {
canvas.context.clearRect(0, 0, canvas.element.width, canvas.element.height);
};
}
now use:
var myGame = new Game();

Categories