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";
}
Related
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
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
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
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();
may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);