JavaScript Closures Manipulation - javascript

I'm doing some Node.js and I want to use the closure representation to create my objects. I think I'm missing something, because something simple like this isn't working:
var Room = function(foo) {
this.name = foo;
this.users= [];
return {
getName : function() {
return this.name;
}
}
}
var room = new Room("foo");
console.log(room.getName());
I also have tried without the parameter.. and still not working.
var Room = function() {
this.name = "foo";
this.users= [];
return {
getName : function() {
return this.name;
}
}
}
var room = new Room();
console.log(room.getName());
However, something like this works:
var Room = function(foo) {
this.name = foo;
this.users= [];
}
var room = new Room("foo");
console.log(room.name);
I can't understand why this isn't working.
--Edited
Thanks to Amadan I have found the right way to do it:
var Room = function() {
var name = "foo";
var users= [];
return {
getName : function() {
return name;
}
}
}
var room = new Room();
console.log(room.getName());
This way "name" and "users" are encapsulated.

return in a constructor will overwrite this. So the right way to do this is:
var Room = function(foo) {
this.name = foo;
this.users= [];
this.getName = function() {
return this.name;
}
}
or
var Room = function(foo) {
return {
name: "foo",
users: [],
getName : function() {
return this.name;
}
}
}
The first one does everything on the original this; the second one replaces this with everything you need.

Related

Javascript context in inner class object

Prior to using ES6 we could instantiate a "class" like so...
var Animal = function(){}
and then...
var dog = new Animal()
the context within the "class" will be the class (instance) itself
var Animal = function( name ){
this.name = name;
this.getName = function(){
// the context here (this) is the class (Animal)
return this.name; // works well
}
}
The question is, if I wouldn't want to pollute the root scope and use sub-objects, for various uses, then the context would become the object in which the function is being kept
var Animal = function( name ){
this.utilities = {
this.getName : function(){
// the context here is the 'utilities' object so...
return this.name // wouldn't work
}
}
}
of course we could always use something in the form of
dog.utilities.getName.call(dog)
but this would be kind of long and uncomfortable...
is there a way to create the 'utilities' object and apply the context to all of its functions to point back to the root scope? without having to use call and apply every time? (an answer without using ES6 would be great...)
One way to ensure that this is what you want it to be in the various utilities functions is to use arrow functions for them, since arrow functions close over the this where they're defined:
class Animal {
constructor(name) {
this.name = name;
this.utilities = {
getName: () => { // This is an arrow function
return this.name; //
} //
};
}
}
const dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"
This is basically the ES2015+ version of the old var t = this; solution:
function Animal(name) {
var t = this;
this.name = name;
this.utilities = {
getName() {
return t.name;
}
};
}
var dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"
In both cases, this means that you're creating new function objects for each individual instance of Animal (the code will be shared between those objects, but the objects are distinct). That's fine unless there are going to be a lot of Animal instances.
Alternately, you could have a helper that you pass the instance to:
const Animal = (function() {
class Utilities {
constructor(animal) {
this.a = animal;
}
getName() {
return this.a.name;
}
}
class Animal {
constructor(name) {
this.name = name;
this.utilities = new Utilities(this);
}
}
return Animal;
})();
const dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"
or
var Animal = (function() {
function Utilities(animal) {
this.a = animal;
}
Utilities.prototype.getName = function getName() {
return this.a.name;
};
return function Animal(name) {
this.name = name;
this.utilities = new Utilities(this);
}
})();
var dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"
...which lets utilities reuse its function objects via Utilities.prototype.
You could probably use the following:
var utilities = function (context) {
return {
getName: function () {
console.log(context.name)
}
}
}
var Animal = function( name ){
this.name = name
this.utilities = utilities.call(null, this)
}
var dog = new Animal('dog')
dog.utilities.getName()
But, if you are okay doing this: dog.getName() instead of dog.utilities.getName() then you might have a cleaner solution (IMO) as follows:
var Animal = function( name ){
this.name = name
}
var utilities = {
getName: function () {
console.log(this.name)
}
};
Object.assign(Animal.prototype, utilities)
var dog = new Animal('dog')
dog.getName()
Let me know if that works. Thanks.
NEW ANSWER:
var UTILITIES = {
getName: function () {
console.log(this.self.name)
}
}
var Animal = function (name) {
this.name = name
this.utilities = Object.create(UTILITIES, {
self: {
value: this
}
})
}
var dog = new Animal('dog')
dog.utilities.getName()
Variation includes the use of a 'self' attribute which points to the instance of interest. Now, this could look more intuitive.
You can use getter methods. I find them very useful for cases where I need formatted value. This way, the utilities/ logic is only known to this class and is not exposed outside.
function Person(fname, lname) {
var _fname = fname;
var _lname = lname;
Object.defineProperty(this, 'fullName', {
get: function(){
return _fname + ' ' + _lname
}
});
Object.defineProperty(this, 'firstName', {
get: function(){
return _fname
},
set: function(value) {
_fname = value;
}
});
Object.defineProperty(this, 'lastName', {
get: function(){
return _lname
},
set: function(value) {
_lname = value;
}
});
}
var person = new Person('hello', 'world');
console.log(person.fullName);
person.firstName = 'Hello';
console.log(person.fullName);
person.lastName = 'World'
console.log(person.fullName);

Javascript function does not return the right value

So i have this code:
function Class1() {
this.i = 1;
var that=this;
function nn() {
return 21;
}
this.aa = function() {
nn();
};
this.bb = function() {
this.aa();
};
this.cc = function() {
this.bb();
};
}
var o = new Class1();
var b=o.cc();
alert(b); //undefined
But when the alert is fired, I get an undefined error and not 21, Does the private method can not use a return? Thanks!
When using the function() {} syntax to define a function, you always explicitly need to return the value, i.e. not only from nn, but from all intermediate functions as well.
function Class1() {
this.i = 1;
var that = this;
function nn() {
return 21;
}
this.aa = function() {
return nn();
}
this.bb = function() {
return this.aa();
}
this.cc = function() {
return this.bb();
}
}
var o = new Class1();
var b = o.cc();
alert(b); // "21"
Apart from the answer above, the 'this' context seems weird in your functions. Maybe you are better of with arrow functions if you dont want to bind the this context to each function. I also think that it is better to actually separate private and public functions when using a 'class' like this.
function Class1() {
var _nn = function () {
return 21;
}
var _aa = function () {
return _nn();
}
var _bb = function () {
return _aa();
}
var cc = function () {
return _bb();
};
return {
cc
};
}
var o = new Class1();
var a = o.cc();
console.log(a);
Much easier to understand that it is only cc that is a public function.
So with arrow function it would instead look like this, and you can use the Class1 this context inside of your private functions without doing
var that = this; or using bind.
function Class1() {
this.privateThing = 'private';
var _nn = () => { return this.privateThing; };
var _aa = () => { return _nn(); };
var _bb = () => { return _aa(); };
var cc = () => { return _bb(); };
return {
cc
};
}

How to write a object oriented Node.js model

I am having a lot of trouble writing an object oriented Cat class in Node.js. How can I write a Cat.js class and use it in the following way:
// following 10 lines of code is in another file "app.js" that is outside
// the folder "model"
var Cat = require('./model/Cat.js');
var cat1 = new Cat(12, 'Tom');
cat1.setAge(100);
console.log(cat1.getAge()); // prints out 100 to console
var cat2 = new Cat(100, 'Jerry');
console.log(cat1.equals(cat2)); // prints out false
var sameAsCat1 = new Cat(100, 'Tom');
console.log(cat1.equals(sameAsCat1)); // prints out True
How would you fix the following Cat.js class I have written:
var Cat = function() {
this.fields = {
age: null,
name: null
};
this.fill = function (newFields) {
for(var field in this.fields) {
if(this.fields[field] !== 'undefined') {
this.fields[field] = newFields[field];
}
}
};
this.getAge = function() {
return this.fields['age'];
};
this.getName = function() {
return this.fields['name'];
};
this.setAge = function(newAge) {
this.fields['age'] = newAge;
};
this.equals = function(otherCat) {
if (this.fields['age'] === otherCat.getAge() &&
this.fields['name'] === otherCat.getName()) {
return true;
} else {
return false;
}
};
};
module.exports = function(newFields) {
var instance = new Cat();
instance.fill(newFields);
return instance;
};
If I were to design an object like this, then I would have done like this
function Cat(age, name) { // Accept name and age in the constructor
this.name = name || null;
this.age = age || null;
}
Cat.prototype.getAge = function() {
return this.age;
}
Cat.prototype.setAge = function(age) {
this.age = age;
}
Cat.prototype.getName = function() {
return this.name;
}
Cat.prototype.setName = function(name) {
this.name = name;
}
Cat.prototype.equals = function(otherCat) {
return otherCat.getName() == this.getName()
&& otherCat.getAge() == this.getAge();
}
Cat.prototype.fill = function(newFields) {
for (var field in newFields) {
if (this.hasOwnProperty(field) && newFields.hasOwnProperty(field)) {
if (this[field] !== 'undefined') {
this[field] = newFields[field];
}
}
}
};
module.exports = Cat; // Export the Cat function as it is
And then it can be used like this
var Cat = require("./Cat.js");
var cat1 = new Cat(12, 'Tom');
cat1.setAge(100);
console.log(cat1.getAge()); // 100
var cat2 = new Cat(100, 'Jerry');
console.log(cat1.equals(cat2)); // false
var sameAsCat1 = new Cat(100, 'Tom');
console.log(cat1.equals(sameAsCat1)); // true
var sameAsCat2 = new Cat();
console.log(cat2.equals(sameAsCat2)); // false
sameAsCat2.fill({name: "Jerry", age: 100});
console.log(cat2.equals(sameAsCat2)); // true
I would use a class :
class Cat {
fields = {
age: null,
name: null
};
fill(newFields) {
for(var field in this.fields) {
if(this.fields[field] !== 'undefined') {
this.fields[field] = newFields[field];
}
}
}
getAge() {
return this.fields.age;
}
setAge(newAge) {
this.fields.age = newAge;
}
}
exports.Cat = Cat;
This code is working fine Person.js code here
exports.person=function(age,name)
{
age=age;
name=name;
this.setAge=function(agedata)
{
age=agedata;
}
this.getAge=function()
{
return age;
}
this.setName=function(name)
{
name=name;
}
this.getName=function()
{
return name;
}
};
call object code:
var test=require('./route/person.js');
var person=test.person;
var data=new person(12,'murugan');
data.setAge(13);
console.log(data.getAge());
data.setName('murugan');
console.log(data.getName());
There is error loop hole in answers by #thefourtheye, I will describe those below
Object modelling rules
Create empty new object
Create Filled Object
Only Initial object should be set by machine/code
After Initial object assignment Any changes in your object should happen by user interaction only.
After Initial object assignment Any changes in object by code without user intention is going to add some bugs
Problem Use case :
Eg - So when you create filled object , at that time if any property(somedate) is not having any value then due to below code the default value gets assigned to it(somedate) , which is against object modelling rules.
Bug
Constructor function is given Dual responsibility to create new
& filled object which he mixes up while creating filled object , And
its going to make mistakes.
Means there is some buggy code in your app that is going to set values by it self without users intention
function Cat(age, name, somedate ) { // Accept name and age in the constructor this.name = name || null; this.age = age || null; this.somedate = somedate || new Date(); //there will be lots of usecases like this }
So to solve this Problem i use below JavaScript data model.
So it allows user to create filled object Or new object intentionally only when need any one of them and not messing with each other
class Cat {
constructor(){
this.name = null;
this.age = null;
}
initModel (data) {
this.name = data.name;
this.age = data.age
}
getAge () { return this.age;}
setAge (age) { this.age = age; }
getName () {this.name;}
setName (name) {this.name = name;}
equals (otherCat) {
return otherCat.getName() == this.getName()
&& otherCat.getAge() == this.getAge();
}
fill (newFields) {
for (let field in newFields) {
if (this.hasOwnProperty(field) && newFields.hasOwnProperty(field)) {
if (this[field] !== 'undefined') {
this[field] = newFields[field];
}
}
}
};
}
let cat1 = new Cat();
cat1.initModel({age : 12,name :'Tom'})
cat1.setAge(100);
console.log(cat1.getAge()); // 100
let cat2 = new Cat();
cat2.initModel({age : 100,name : 'Jerry'})
console.log(cat1.equals(cat2)); // false
let sameAsCat1 = new Cat({age : 100,name : 'Tom'});
sameAsCat1.initModel({age : 100,name : 'Tom'})
console.log(cat1.equals(sameAsCat1)); // true
let sameAsCat2 = new Cat();
console.log(cat2.equals(sameAsCat2)); // false
sameAsCat2.fill({name: "Jerry", age: 100});
console.log(cat2.equals(sameAsCat2));
Note :
Constructor is only used For creating new Object
InitModel is only used For creating filled Object

Inherit and reuse object oop

I want to inherit from Button by prototype. But alerted name stays "Sarah" as it is the last Child created. Creator Class should set the name with Method in Button. Jsfiddle: JSFIDDLE
function Creator() {
var c1 = new Child();
c1.SetName("Albert");
c1.SetStandardClickHandler();
var c2 = new Child();
c2.SetStandardClickHandler();
c2.SetName("Sarah");
}
Child.prototype = new Button();
function Child() {
this._layout = $('<div>child</div>');
}
function Button() {
var that = this;
var _name;
this.SetName = function (name) {
_name = name;
}
this.SetStandardClickHandler = function () {
this._layout.click(function () {
alert(_name);
});
};
}
var c = new Creator();
var _name is a static variable.
Try something like this instead:
function Button() {
var that = this;
this.name = null;
this.SetName = function (name) {
this.name = name;
}
this.SetStandardClickHandler = function () {
this._layout.click(function () {
alert(that.name);
});
};
}
Or you can reorganize to something like this:
var Button = (function() {
function Button() {
this.name = null;
}
Button.prototype.SetName = function (name) {
this.name = name;
}
Button.prototype.SetStandardClickHandler = function () {
var that = this;
this._layout.click(function () {
alert(that.name);
});
};
return Button;
});
This should get you started:
(function() {
'use strict';
var Button = function (name) {
this.name = name || ''; // Set name to contructor value or empty string
};
Button.prototype.setName = function (name) {
this.name = name;
};
Button.prototype.setDefaultClickListener = function () {
this._layout.click(function () {
alert(this.name);
}.bind(this));
};
var Child = function (name) {
Button.call(this, name); // Call parent object construtor on new instance of Child
this._layout = $('<div>child</div>');
};
Child.prototype = Object.create(Button.prototype); // Inherit from Button prototype
Child.prototype.constructor = Child; // Reset constructor to Child
var albert = new Child('Albert');
albert.setDefaultClickListener();
var sarah = new Child('Sarah');
sarah.setDefaultClickListener();
})();

encapsulation in javascript module pattern

I was reading this link http://addyosmani.com/largescalejavascript/#modpattern
And saw the following example.
var basketModule = (function() {
var basket = []; //private
return { //exposed to public
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
},
getTotal: function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
}());
basketModule.addItem({item:'bread',price:0.5});
basketModule.addItem({item:'butter',price:0.3});
console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());
It stats that "The module pattern is a popular design that pattern that encapsulates 'privacy', state and organization using closures" How is this different from writing it like the below? Can't privacy be simply enforced with function scope?
var basketModule = function() {
var basket = []; //private
this.addItem = function(values) {
basket.push(values);
}
this.getItemCount = function() {
return basket.length;
}
this.getTotal = function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
var basket = new basketModule();
basket.addItem({item:'bread',price:0.5});
basket.addItem({item:'butter',price:0.3});
In the first variant you create an object without the possibility to create new instances of it (it is an immediately instantiated function). The second example is a full contructor function, allowing for several instances. The encapsulation is the same in both examples, the basket Array is 'private' in both.
Just for fun: best of both worlds could be:
var basketModule = (function() {
function Basket(){
var basket = []; //private
this.addItem = function(values) {
basket.push(values);
}
this.getItemCount = function() {
return basket.length;
}
this.getTotal = function(){
var q = this.getItemCount(),p=0;
while(q--){
p+= basket[q].price;
}
return p;
}
}
return {
basket: function(){return new Basket;}
}
}());
//usage
var basket1 = basketModule.basket(),
basket2 = basketModule.basket(),

Categories

Resources