Private members in JavaScript object with getters and setters - javascript

I am testing an JS object
gl.test = function () {
var $ = jQuery;
var _private = null;
var _setStr = function ( t ) {
_private = t;
}
var _getStr = function() {
return _private;
}
var obj = {
init: function ( str ) {
_setStr(str);
},
test: function() {
console.log( _getStr() );
},
EOF: null
};
return obj;
}();
When executing the following:
var test1 = gl.test;
var test2 = gl.test;
test1.init('test1');
test2.init('test2');
test1.test();
test2.test();
the result comes back as test2 test2
This being an object I would expect for the order of execution not to matter and would expect for test1 and test2 to be returned as per:
var test1 = gl.test;
test1.init('test1');
test1.test();
var test2 = gl.test;
test2.init('test2');
test2.test();
Am I doing something wrong here?

As noted in the comments, you're not instantiating a new instance of gl.test. You could change it to not be an IIFE and use the new keyword
var gl ={}
gl.test = function () {
....
}
var test1 = new gl.test();
var test2 = new gl.test();
Live example: http://jsfiddle.net/19f9504u/

because test1 and test2 is the same object
// remove the autocall function and do this to gl.test
var test1 = gl.test();
var test2 = gl.test();
But it does not that how clases work in javascript by the way

Related

Adding numbers in an object is not working as expected in JS

I created an object with Int values and some functions in js as below
var obj = function (int1,int2,int3){
this.int1=int1;
this.int2=int2;
this.int3=int3;
this.add= (function (){
return parseInt(int1)+parseInt(int2)+parseInt(int3)
}());
When I execute the code
var a= new obj(1,2,3);
console.log(a.add);
The Answer is
NaN
Type of all the int1,int2.int3,add is Number.
Whats the problem with My code & How to correct it
You need a instance of the function with new operator and you could skip parseInt, which works better with a given base.
var Obj = function (int1, int2, int3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.add = function () {
return this.int1 + this.int2 + this.int3;
}
},
instance = new Obj(1, 2, 3);
console.log(instance.add());
Try this:
var obj = function(int1, int2, int3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.add = function() {
return parseInt(int1) + parseInt(int2) + parseInt(int3)
}};
And, Call above as:
var a = new obj(1, 2, 3);
console.log(a.add());
run this code:
var obj = function (int1, int2, int3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.add = (function () {
return parseInt(int1) + parseInt(int2) + parseInt(int3)
} ())
};
var a = new obj(1,2,3);
console.log(a.add); // 6
your code lost a }
Try this it's working fine :
var obj = function (int1,int2,int3){
this.int1=int1;
this.int2=int2;
this.int3=int3;
this.add= (function (){
return parseInt(int1)+parseInt(int2)+parseInt(int3)
}())
}
var a= new obj(1,2,3);
console.log(a.add); // 6
Working fiddle :
https://jsfiddle.net/90ku8qae/
Update :
You forgot to add the closing bracket for the function obj. I just added and everything is working fine now.

Javascript: Calling private in a outside javascript file with JSON data

I am trying to call the method getTitulo, getDuracion and getLink inside the cancion.js file but when i call the function it returns the following error: "listaCanciones_Lcl[i].getTitulo is not a function". I have searched in different websites but i didnt got lucky with finding an answer. Hopefully someone here can give me some help, i will gladly appreciate it!
//Logic.js file
var listaCanciones = [],
ejecuTitulo = '',
ejecuDuracion = '',
ejecuLink = '';
var btnGenerarLista = document.getElementById("addList").addEventListener("click", agregarCanc);
var btnAgregarLista = document.getElementById("gnrList").addEventListener("click", llenarTabla);
function agregarCanc (){
var nameSong = document.querySelector('#nameSong').value;
var duraSong = document.querySelector('#duraSong').value;
var linkSong = document.querySelector('#linkSong').value;
var objCancion = new Cancion(nameSong, duraSong, linkSong);
listaCanciones.push(objCancion);
var listaCancionesJson = JSON.stringify(listaCanciones);
localStorage.setItem('json_canciones', listaCancionesJson);
}
function llenarTabla (titulo){
var celdaTitulo = document.querySelector('#tituloList'),
celdaDuracion = document.querySelector('#duracionList'),
celdaLink = document.querySelector('#linkList'),
listaCanciones_Lcl = JSON.parse(localStorage.getItem('json_canciones'));
for(var i=0; i<listaCanciones_Lcl.length;i++){
// Acceder a lista canciones
I am getting an error in this line, where is says "getTitulo" is not a function but i dont really know why?
var nodoTextoTitulo = document.createTextNode(listaCanciones_Lcl[i].getTitulo()),
nodoTextoDuracion = document.createTextNode(listaCanciones_Lcl[i].getDuracion()),
nodoTextoLink = document.createTextNode(listaCanciones_Lcl[i].getLink());
// Create td
var elementoTdTitulo = document.createElement('td'),
elementoTdDuracion = document.createElement('td'),
elementoTdLink = document.createElement('td');
// Celda Id Append Child
elementoTdTitulo.appendChild(nodoTextoTitulo);
elementoTdDuracion.appendChild(nodoTextoDuracion);
elementoTdLink.appendChild(nodoTextoLink);
// Fila Append Child
celdaTitulo.appendChild(elementoTdTitulo);
celdaDuracion.appendChild(elementoTdDuracion);
celdaLink.appendChild(elementoTdLink);
}
}
//Cancion.js File
var Cancion = function(pTitulo, pDuracion, pLink){
var id = 0;
var titulo = pTitulo;
var duracion = pDuracion;
var link = pLink;
this.getId = function (){
return id;
};
this.setTitulo = function (pTitulo){
titulo = pTitulo;
};
this.getTitulo = function(){
return titulo;
};
this.setDuracion = function(pDuracion){
duracion = pDuracion;
};
this.getDuracion = function(){
return duracion;
};
this.setLink = function (pLink){
link = pLink;
};
this.getLink = function(){
return link;
};
};
First, make sure you are loading the Cancion.js file before the others in your HTML. Your problem is that when you parse the JSON back out of local storage, Cancion is not a known object, so getTitulo is undefined. You'll have to do listaCanciones_Lcl[i].titulo; instead.
And another change you'll need is to loosen the scope of your variables. The reason you need this.x = pX is because before JSON.stringify(new Cancion(1, 2, 3)) just returned "{}". With this code it returns "{"id":0,"titulo":1,"duracion":2,"link":3}", which I think is what you were after.
function Cancion(pTitulo, pDuracion, pLink){
this.id = 0;
this.titulo = pTitulo;
this.duracion = pDuracion;
this.link = pLink;
this.getId = function (){
return this.id;
};
this.setTitulo = function (pTitulo){
this.titulo = pTitulo;
};
this.getTitulo = function(){
return this.titulo;
};
this.setDuracion = function(pDuracion){
this.duracion = pDuracion;
};
this.getDuracion = function(){
return this.duracion;
};
this.setLink = function (pLink){
this.link = pLink;
};
this.getLink = function(){
return this.link;
};
};
var objWithFunction = {
name: 'Object with Function',
getName: function() { return this.name }
};
undefined
objWithFunction.getName() // --> "Object with Function"
var string = JSON.stringify(objWithFunction)
string // -=> "{"name":"Object with Function"}"
JSON is for data only..
Better you create a model, and fill it with data.. but this model has to exist in your application.. or you load the model parallel to your data..
function SomeThing() {};
SomeThing.prototype.getName = function() { return this.name };
var Thing1 = new SomeThing(JSON.parse("{name:'ThingOne'}"));
Thing1.getName(); // ThingOne

javascript new does not create new object

I am trying to get two objects from the same class definition. However they seem to share the same attribute. What can i do?
http://jsfiddle.net/dagod/nuam8dks/2/
myclass = function() {
this.data.push(Math.random(1000));
};
myclass.prototype.data = [];
a = new myclass();
b = new myclass();
console.log(a.data);
console.log(b.data); //same as a.data
I've just been doing this for something else!
myclass = function() {
this.data = [];
};
Now you can access it my simply doing myclass.data =
Personally this is how i'd do it:
var MyNameSpace = {
SomeFunction: function() {
Some code
};
this.somevariable = somevalue;
};
Then you can go myNameSpace.myfunction() or myNameSpace.myVar = Value
See the comment from elclanrs.
var Myclass = function() {
this.data = [];
this.data.push(Math.random(1000));
};
You need to declare your member variable inside the constructor instead of making them part of the prototype. oop in javascript can be ugly and unintuitive. (Thats why there are so many oop libraries out there for javascript)
Using ds.oop
ds.make.class({
type: 'MyClass',
constructor: function(x){
this.a = x;
}
});
var c1 = new MyClass(1);
var c2 = new MyClass(2);
console.log( c1.a ); // output: 1
console.log( c2.a ); // output: 2
You can get the desired results as follows:
myclass = function() {
this.data = Math.random(1000);
};
//myclass.prototype.data = [];
var a = new myclass();
var b = new myclass();
jsfiddle

call javascript object function

I have two objects of the same type.
function myObject(){
this.a = 1;
this.b = 1;
function changeA(){//some code};
function changeB(){//some code};
}
var obj1 = new myObject();
var obj2 = new myObject();
How can I make a call to obj2.changeB() from external code, another function or another object (e.g. obj1) ?
obj2.changeB() doesn't exist.
You need to assign a property on your object, not create a local variable:
this.changeB = function() { ... };
Just create a properties in you object like:
function myObject(){
this.a = 1;
this.b = 1;
this.functionA = function changeA(){//some code
alert('im 1');
};
this.functionb = function changeB(){//some code
alert('im 2');};
}
and call the function obj2.functionb();
LIVE DEMO
You have to do something like that:
var myObject = function(){
var protectedValue1 = ‘variable’;
var protectedValue2 = ‘variable’;
var changeA = function(){
alert(protectedValue);
}
var changeB = function(){
alert(protectedValue);
}
}
var object1 = new myObject();
var object2 = new myObject();
//
object2.changeB();

Create function/object in javascript

How I can create a thing which is both function and object at a same time?
Suppose its name is obj.
In the following context it is a object:
obj.key1 = "abc";
obj.key2 = "xyz";
And in another context it is a function like this:
var test = obj("abc");
How I can create this object in JavaScript?
function obj( param ){
var that = this;
that.key1 = "default";
that.key2 = "default";
that.someMethod = function(){
return param;
};
that.showMessage = function(){
alert( param );
};
return that;
}
and then:
var test = obj("hi there");
test.key1 = "abc";
test.key2 = "xyz";
test.showMessage();
FIDDLE: http://jsfiddle.net/Xnye5/
or
obj("hi there again").showMessage();
FIDDLE: http://jsfiddle.net/Xnye5/1
Like this:
function obj( param ) {
console.log( param );
}
obj.prototype.key1 = "abc";
obj.prototype.key2 = "xyz";
var test = new obj( "abc" );
console.log( test.key1 );
console.log( test.key2 );
Key new needed to save function context. You can use return this in function to avoid this.
Or using this instead of prototype:
function obj( param ) {
console.log( param );
this.key1 = "abc";
this.key2 = "xyz";
}

Categories