js code shows error after creating new instance of object - javascript

When I create new instance of ClickEvent object it returns following error. Click here for jsfiddle code. Below is my code
var ClickEvent = function (event) {
this.ev = $('.' + event);
this.ev.on('click', this.userInput());
};
ClickEvent.protoype = function () {
return {
userInput: function () {
console.log('user');
},
show: function () {
console.log('show');
}
};
}();
var c = new ClickEvent('event');
c.show();
Why does it show this error and how can I solve it?
Uncaught TypeError: Object [object Object] has no method 'userInput'

There are a couple of issues.
You have a typo in prototype.
this.ev.on('click', this.userInput()); should be this.ev.on('click', this.userInput); - you want to pass a reference to the function so it's executed when the user clicks, you don't want to call it when binding the event handler.

You spelt prototype wrong; your code otherwise executes fine, though you meant to reference the method with this.userInput rather than invoking it right away with this.userInput(), and due to this you get both messages 'show' and 'user' when the page loads.
With those fixes in place, your code functions as I expect you intend: the 'user' only appears when you click on the link.

The error means that no where in the javascript library, a method userInput can be found. Which I can tell is very likely since you have not referenced the userInput variable anywhere before line 3. Also the .on() has two parameters: ("EVENT", "FUNCTION"). In your code, this.userInput is not a function and cannot function as one.

fixed Type, and a little change , this works.
function ClickEvent(event) {
this.ev = $('.' + event);
this.ev.on('click', this.userInput());
};
ClickEvent.prototype = {
userInput: function () {
console.log('user');
},
show: function () {
console.log('show');
}
};
var c = new ClickEvent('event');
c.show();

Related

Strange Function Behavior with Prototype and Event Listeners - JavaScript [duplicate]

This question already has answers here:
The value of "this" within the handler using addEventListener
(10 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
Original Modal
I want to use a universal app object. To this empty object I will add functions as needed. The issue is that some functions will need to all others within the app object.
So, my question is: how do I construct a large object without having to define all functions inside the object at the time of creation? I would like to split up the chunks of code to not have one astronomical long .js file.
There is a simple example of my original code:
var app = {
tow: function () {
return true;
},
one: function () {
return this.tow();
}
};
// app.one() => returns true
Updated Modal
Here is something I found interesting. I was playing around with the prototype modal and discovered something strange. When I use this model I can add functions that can call other added functions. But, when I create an event listener it is unable to run the code. Can anyone explain why this is?
Modified code with unexpected result:
function modal () {}
modal.prototype.one = function () {
return this.two();
};
modal.prototype.two = function () {
return "cool";
};
modal.prototype.init = function () {
document.getElementById('go')
.addEventListener("click", this.one);
}
var app = new modal();
app.init();
// app.one() => returns true
// event listener => returns "TypeError: this.two is not a function"
JSBIN: https://jsbin.com/vureruziza/edit?js,console,output
this.one called as you done refers to addEventListener function, not to your object. This will solve the issue
modal.prototype.init = function () {
var self = this;
document.getElementById('go')
.addEventListener("click", function(){
self.one()
});
}
bind the click function with this cause the function will need the this context, not the window context. Then call your this.one function in de click handler.
function modal () {}
modal.prototype.one = function () {
return this.two();
};
modal.prototype.two = function () {
return "cool";
};
modal.prototype.init = function () {
document.getElementById('go')
.addEventListener("click", function(e){
console.log(this.one())
}.bind(this));
/*
The following wil also be called but your return value
of your this.one function won't be captured. But your code will run.
.addEventListener("click", this.one.bind(this));
Try replacing it with the above and put a debugger statement in this.one
and see that the code will actualy be ran, just not captured to output.
*/
}
var app = new modal();
app.init();
// app.one() => returns true
// event listener => returns "TypeError: this.two is not a function"
<div id="go">go</div>
Use ES6 fat arrow function. Update modal.prototype.init as below -
modal.prototype.init = function () {
document.getElementById('go')
.addEventListener("click", () => this.one());
}
Edit - If you wanted to debug the issue, you could just console.log the this value in function one like so -
modal.prototype.one = function () {
console.log(this);
return this.two();
};
You will most likely see the window object. You will certainly not see the modal object.

Return value from the prototype function in javascript

This is my function, I'm trying to return a value.
var operations = function() {
this.selectedQueryBy = function() {
return jQuery('input[type="radio"][name="selectRadio"]:checked').attr("id")
},
this.submitForm = function() {
jQuery('.btns').hide();
var queryBy = this.selectedQueryBy;
}
}
Im trying to get the value of "selectedqueryby" which is already defined in the function. It returns the whole function instead of the radio button. Is the calling way correct?
Please let me know where Im doing wrong.
I'll call the submitForm event on clicking a button.
You need to add parentheses to call the function:
var queryBy = this.selectedQueryBy();
// ^^
Otherwise you're just referring to the function itself instead of calling it.

Can I put a method as the argument in the setInterval function?

Preety straight forward question, though I can't find the answer anywhere
I tried these two ways:
setInterval(function(){object/*or this*/.method()},500)
and
setInterval('object/*or this*/.method()',500)
setInterval in fact expects a method as the first argument, though there is an alternative syntax where the first argument can be a string of code (not recommended by most)
If you're having issues with that code, it may have to do with the scope of 'this'
setInterval(function(){this.method()},500)
In the above code, 'this' will refer to the closure itself, and wouldn't be the same as 'this.method' occurring outside of that closure. For example, the following would work:
function MyClass() {
this.thingy = 'yep this is a thingy'
}
var myClass = new MyClass()
// Will log 'MyClass yep this is a thingy'
setInterval(function() { console.log('MyClass', myClass.thingy) }, 1000)
Whereas the following will not work (presuming instantiating the object and calling foo()):
function MyOtherClass() {
this.thingy = 'also a thingy'
}
// Will log 'MyOtherClass undefined'
MyOtherClass.prototype.foo = function() {
setInterval(function() { console.log('MyOtherClass', this.thingy) }, 1000)
}
The second example will work if we get around using 'this' within the closure (presuming instantiating the object and calling bar()):
MyOtherClass.prototype.bar = function() {
var that = this
setInterval(function() { console.log('MyOtherClass', that.thingy) }, 1000)
}
Also be sure that setInterval is being passed the name of a function:
setInterval(someFunction, 500)
rather than executing a function as an argument
setInterval(someFunction(), 500)
This last line of code is usually a mistake, unless someFunction() returns a function itself ;)
The difference between your 2 ways for passing a function to setInterval is whether you want to pass your function as refrence of just copy of it. Allow me to explain it by example:
-1 Referring(demo):
var obj = {
testMethod: function () {
console.log('function (testMethod): intial output');
}
}
setInterval(function () {
obj.testMethod()
}, 1000);
obj.testMethod = function () {
console.log('function (testMethod): changed output');
}
when you run this code, the result 'll be execution of the modified version of testMethod. Because here you dont copy the function! Instead, you refer to it. So whenever function implementation is changed, the last modified version is executed.
-2 Copying(demo):
var obj = {
testMethod: function () {
console.log('function (testMethod): intial output');
}
}
setInterval(obj.testMethod, 1000);
obj.testMethod = function () {
console.log('function (testMethod): changed output');
}
Here all you do is you are passing a copy of the last defined version of the function testMethod to setInterval. So whatever changes you do to testMethod, the result of setInterval will not be changed.

Immediate object initialization confusion

I am working on a js file that makes use of JScroll. The callback for the jsp-scroll-y event is defined in the following function
function initWall() {
//callback from jqueryscrollpane
Scroll_TimeLine_Instance = function (event, scrollPositionY, isAtTop, isAtBottom){
//get more content
if (isAtBottom) {
GetMoreDate(objid, vwrsid, secid, orgid, incflwr, qty, mintlid, maxtlid, successGetTimeLineCallback, failureGetTimeLineCallback);
}
}();
}
Another function is defined that then binds this callback to the jsScroll
function reapplyScroll() {
Utilities.DestroyScrollBar($(_target).closest('.widgetBody'));
Utilities.ApplyScrollBar($(_target).closest('.widgetBody'), false, Scroll_TimeLine_Instance);
}
Utilities.ApplyScrollBar = function (element, showScrollBar, scrollCallback) {
$(element).jScrollPane({
horizontalGutter: 5,
verticalGutter: 5,
'showArrows': false
}).bind('jsp-scroll-y', scrollCallback);
if (!showScrollBar) {
$(element).find('.jspDrag').hide();
}
}
The callback was never called, and I found this was because it was undefined. If I remove the Immediate object initialization (); from after the creation of the function everything works fine.
Can anyone explain this? I don't understand why it was being called immediate anyway, so i assume this is an error on the part of whoever created it, and I have no idea why it would cause this variable to be undefined?
It is undefined because the function (that is immediately called) does not return any value
So it seems indeed that this is a bug of the library..
Either remove the (); at the end, or if you want to call it right there as well just invoke it in the following line
function initWall() {
//callback from jqueryscrollpane
Scroll_TimeLine_Instance = function (event, scrollPositionY, isAtTop, isAtBottom){
//get more content
if (isAtBottom) {
GetMoreDate(objid, vwrsid, secid, orgid, incflwr, qty, mintlid, maxtlid, successGetTimeLineCallback, failureGetTimeLineCallback);
}
}; /// this is assigning the function to our variable
Scroll_TimeLine_Instance (); // this is the invokation
}

Why is this javascript method firing even when I'm not calling it?

Just trying to get my head around Javascript a very strange thing has happened. The method getChapters() is firing even though I haven't explicitly called it...Any ideas? (I'm getting the alert box for get chapters).
videoChapters = function () {
};
videoChapters.prototype.config = {
jsonProvider : '_Chapters.aspx'
};
videoChapters.prototype.init = function () {
//get chapters
};
videoChapters.prototype.getChapters = new function () {
alert('getting chapters');
}
jQuery(document).ready(function () {
videoChapters = new videoChapters();
videoChapters.init();
});
This line:
videoChapters.prototype.getChapters = new function () {
...should probably not contain the word 'new'. When Javascript attempts to evaluate the expression, it passes the result of your function to the 'new' operator.
Remove the new keyword:
videoChapters.prototype.getChapters = function () {
alert('getting chapters');
}
....prototype.getChapters = new function () {
^-------- See the new keyword here?
Remove the new keyword and everything will work as expected, using new will invoke the function as an constructor and return a new instance of it, in this case a new instance of an anonymous function.

Categories