Object #<HTMLInputElement> has no method 'initialize' - javascript

I am getting has no method error
here is the sample code
var snake = function(){
this.initialize = function(){
// initalize
};
this.start = function() {
this.initialize();
};
};
var s = new snake();
var startButton = document.getElementByID("start");
startButton.addEventListener('click',s.start,false);
So when I click start button I am getting
Uncaught TypeError: Object # has no method 'initialize'
how can i fix this

Try
startButtons.addEventListener('click', function() { s.start() }, false);
The this in the function is going to be the input unless you use bind

Because of this. Use a private variable(snk) to ensure you are accessing the snake:
var snake = function(){
var snk = this;
this.initialize = function(){
// initalize
};
this.start = function() {
snk.initialize();
};
};
var s = new snake();
var startButton = document.getElementByID("start");
startButton.addEventListener('click',s.start,false);

Related

Function keeps return NaN

When the window loads, the console is returning indexIn.But when I run the bottom function, it returns NaN.
const recentItem = document.querySelector('.recent-item');
var indexIn;
window.onload = function() {
var indexIn = JSON.parse(localStorage.getItem("indexInStore"));
var indexOut = JSON.parse(localStorage.getItem("indexOutStore"));
var indexIn = Number(indexIn);
console.log(indexIn);
}
var indexIn = indexIn;
recentItem.addEventListener('click', function() {
console.log(indexIn);
});
Can you try:
const recentItem = document.querySelector('.recent-item');
var indexIn;
window.onload = function() {
indexIn = Number(JSON.parse(localStorage.getItem("indexInStore")));
var indexOut = JSON.parse(localStorage.getItem("indexOutStore"));
console.log(indexIn);
}
recentItem.addEventListener('click', function() {
console.log(indexIn);
});
You have indexIndefined globally then your are "redefining" it and setting in inside an "onload" function. Not good coding.

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 inheritance - '...is not defined'. Namespace issue?

I have a 'class' called ModuleSelector that grabs a list of modules from a server and displays them as clickable toggle buttons. I'm trying to create a class called Module that extends the ToggleButton class and is only visible to the ModuleSelector.
The problem I'm having is that the line:
Module.prototype = new ToggleButton(); is giving an error: ToggleButton is not defined.
I don't understand why it cannot be found, because I can create new instances of ToggleButton inside the Module function, for example.
ModuleSelector.js
(function() {
function Module(id,name){
this.moduleID = id;
this.moduleName = name;
this.topics = [];
this.addTopic = function(topic){
this.topics.push(topic);
}
}
Module.prototype = new ToggleButton();
Module.prototype.constructor = Module;
var ModuleSelector = function (id) {
this.initialize(id);
};
var p = ModuleSelector.prototype = new createjs.Container();
p.Container_initialize = p.initialize;
p.initialize = function (id) {
this.Container_initialize();
//.....
};
window.ModuleSelector = ModuleSelector;
}());
ToggleButton.js
(function() {
var ToggleButton = function(text) {
this.initialize(text);
//....code
};
var p = ToggleButton.prototype = new createjs.Container();
p.Container_initialize = p.initialize;
p.initialize = function(text) {
this.Container_initialize();
};
window.ToggleButton = ToggleButton;
}());

multi inherit or access the property and method outside the object

var ob = function(){
};
ob.prototype.func = function(){
};
var t = function(){
this.p=0;
this.function1(){
}
var a=new ob();
a.func=function(){//overrides the func
//hope to access this.p this.function1
}
};
is it possible to make a can access this.p this.function1 ?
Your comment welcome
You need to keep a reference to this from inside t if you want to access it within a.func. Try the following:
var t = function(){
var this_t = this; // Use this_t to access this.p and this.function1 inside a
this.p=0;
this.function1 = function(){
}
var a=new ob();
a.func = function(){//overrides the func
this_t.p = 1;
this_t.function1();
}
};

Cloned objects and reference inside functions

I am trying to do the following:
var element = {};
element.attrA = 'A';
element.attrB = 1;
element.autoAdvance = function(){
var that = this;
setInterval(function(){
that.attrB++;
},100);
}
element.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
Now I can do the following just fine:
var e1 = element.instance();
var e2 = element.instance();
e1.attrA = 'not e2s business';
e2.attrA = 'not e1s attrA';
The trouble starts when I try to use autoAdvance:
e1.autoAdvance();
will start the autoAdvance for all cloned 'instances' of element. I am sure this is probably rather trivial but I just don't know how to refer to the parent object inside my autoAdvance-function in a way that it gets properly cloned and only affects the instance. Thanks!
EDIT:
This is the actual code I am using:
var player = {};
player.sprites = {};
player.sprites.back = ['img/playerback_01.png','img/playerback_02.png','img/playerback_03.png'];
player.sprites.head = ['img/playerhead_01.png','img/playerhead_02.png','img/playerhead_03.png'];
player.back = new Image();
player.back.src = player.sprites.back[0];
player.head = new Image();
player.head.src = player.sprites.head[0];
player.loop = function(){
var that = this;
var loop = setInterval(function(){
//remove the [0] state from the sprite array and add it at [2]
var state = that.sprites.head.shift();
that.sprites.head.push(state);
state = that.sprites.back.shift();
that.sprites.back.push(state);
that.back.src = that.sprites.back[0];
that.head.src = that.sprites.head[0];
}, 100);
}
player.x = 0;
player.y = 0;
player.instance = function(){
var clone = $.extend(true, {}, this);
return clone;
}
I generate two players:
var player1 = player.instance();
var player2 = player.instance();
But what is happening is that when I use:
player1.loop();
The animation for player2 will start to play as well.
I suggest you start using "class" in JavaScript. They are more or less a function.
function Player(){
this.sprites={};
......
}
Player.prototype.loop=function(){
....
}
var player1=new Player();
var player2=new Player();
player1.loop();
player2.loop();// this should work better
It doesn't really answer your question but it's an alternative way to write code in a cleaner and better way.

Categories