This question already has answers here:
Set "this" variable easily?
(5 answers)
Closed 6 years ago.
I am trying to find out the class of an element when hovered over, and I am getting a
TypeError: undefined is not an object (evaluating 'classString.split')
console error. Here is my code.
function findClass(){
var classString = $(this).attr('class');
var myClass = classString.split(' ')[0];
alert(myClass);
}
//blog
$(".img2.blog").mouseenter(function() {
$('.img2.blog').css('opacity', '0');
$('.img1.blog').removeClass('hidden');
findClass(this);
});
//albums
$(".img2.albums").mouseenter(function() {
$('.img2.albums').css('opacity', '0');
$('.img1.albums').removeClass('hidden');
findClass(this);
});
//videos
$(".img2.videos").mouseenter(function() {
$('.img2.videos').css('opacity', '0');
$('.img1.videos').removeClass('hidden');
findClass(this);
});
//contact
$(".img2.contact").mouseenter(function() {
$('.img2.contact').css('opacity', '0');
$('.img1.contact').removeClass('hidden');
findClass(this);
});
Not sure how to pass "this" as an argument. Any help appreciated.
You can pass this, by using the call method:
findClass.call(this);
Someone will soon say it also works with apply. They only differ in how to pass the real arguments to the function (in case that were needed).
Check out the documentation on the two.
And to add one other method of the same family, with bind you can also achieve it:
findClass.bind(this)();
You still have to let the function know what the parameter is:
function findClass(self) {
var classString = $(self).attr('class');
var myClass = classString.split(' ')[0];
alert(myClass);
}
Use call or apply function.
Here is a slightly modified example that demonstrates how you can do this:
function findClass(){
var classString = this['class'];
var myClass = classString.split(' ')[0];
alert(myClass);
}
findClass.call({'class': "Hello World"})
findClass.apply({'class': "Hello World"})
Related
I can't figure out how to use a Javascript constructor method in a jQuery .click method. I'm trying to get a button's function to change dynamically based on a constructor. Here's the set up:
<button onclick="">
</button>
needs to call a method that changes depending on another button. The following is my broken code:
function GloveMode (name , array) {
this.colorArray = array;
this.displaySettings = function(){
//Title
$("#displayTitle").text(this.name);
//Display Color Set
$("#displayColors").empty();
//Totally Broken
$("#upArrow").click( function(){
addColor();
});
};
this.addColor = function(){
console.log(this.colorArray.length);
};
};
I can't figure out how to get $("#upArrow").click() to call this.colorArray properly, or how to call this.addColor() in the .click() method! Please help.
Your Problem is that "this" means something different in each function body. So save the wanted "this" to a variable e.g. "self" and use that.
function GloveMode (name , array)
{
var self = this;
this.colorArray = array;
this.displaySettings = function()
{
//Title
$("#displayTitle").text(this.name);
//Display Color Set
$("#displayColors").empty();
//Totally Broken
$("#upArrow").click( function()
{
self.addColor();
});
};
this.addColor = function()
{
console.log(self.colorArray.length);
};
};
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I understand how this works when invoked on an object, but I'm having trouble understanding how this works when called from a "static" context.
Given the following HTML:
<body onload="myOnLoad()">
<div id="someDiv">0</div>
</body>
...and this javascript:
function myOnLoad() {
var inc = new Incrementer();
/*** increase() works fine here, "this" refers to "inc" ***/
inc.increase();
inc.setOnClick();
}
function Incrementer() {
this.value = 0;
}
Incrementer.prototype.setOnClick = function() {
/*** increase fails to update someDiv when clicked.
"this" is not "inc" ***/
document.getElementById("someDiv").onclick = this.increase;
}
Incrementer.prototype.increase = function() {
document.getElementById("someDiv").innerHTML = ++this.value;
}
...clicking on someDiv turns it's innerHTML into NaN. I realize that this is because the onclick event is unaware of the existence of inc, but what I don't understand is how to pass 'inc' into the onclick event.
Do you know how I can access inc's variables from the context of an onclick? Or, is there a more conventional way of doing this?
I'm mostly interested in learning how I can make someDiv's onclick refer to that specific instance, inc.
this refers to the context of where the function being called, e.g. in setOnClick the function this.increase will be called in the context of someDiv, so this.value would be undefined in that case.
try
document.getElementById("someDiv").onclick = this.increase.bind(this);
You may want to learn more about the property of this from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
In event handlers, this is bound to the element that triggered the event. If you want to affix it to your this, you need to use .bind() like so:
Incrementer.prototype.setOnClick = function() {
document.getElementById("someDiv").onclick = this.increase.bind(this);
}
You can try another way. You can avoid to use the property prototype and pass the html element to Incrementer at the declaration :
function myOnLoad() {
var inc = new Incrementer(document.getElementById("someDiv"));
}
function Incrementer(newElement) {
var value = 0;
var element = newElement;
this.increase = function(){
element.innerHTML = ++value;
}
element.onclick = this.increase;
}
This might seem like a noob question but I'm not sure what to do. I have function with 2 variables.
function someInfo(myVar1,myVar2)
{
this.lmyVar1=myVar1;
this.myVar2=myVar2;
}
myInstance=new someInfo("string1","string2");
function drawVariables(){
document.write(myInstance.myVar1);
document.write(myInstance.myVar2);
}
I want to use the same drawVariable() for multiple instances. I just can't figure out how the exact syntax for that. How can I make drawVariable() use a different instance of someInfo without repeating anything? Is there a simple example or tutorial I can follow?
Add an argument to the definition of function drawVariables. In the code below, this argument is called info. Now you can use info as your object inside the drawVariables function, and while calling drawVariables function, you can pass whatever instance you want to pass it. drawVariables function would now work with whatever instance you pass it while calling.
function someInfo(myVar1,myVar2)
{
this.myVar1=myVar1;
this.myVar2=myVar2;
}
// Create two separate instances
myInstance=new someInfo("string1", "string1");
myInstance2 = new someInfo("string2", "string2");
// info is the argument that represents the instance passed to this function
function drawVariables(info){
alert(info.myVar1 + ", " + info.myVar2);
}
// Call the function twice with different instances
drawVariables(myInstance);
drawVariables(myInstance2);
See http://jsfiddle.net/WLHuL/ for a demo.
function drawVariables(instance){
document.write(instance.myVar1);
document.write(instance.myVar2);
}
Would it make sense for you to do it this way?
function someInfo(myVar1, myVar2)
{
this.lmyVar1 = myVar1;
this.myVar2 = myVar2;
this.drawVariables = function ()
{
document.write(this.lmyVar1);
document.write(this.myVar2);
}
}
function Test()
{
var obj1 = new someInfo("aaa", "bbb");
var obj2 = new someInfo("xxx", "zzz");
obj1.drawVariables();
obj2.drawVariables();
}
I am trying to select certain property of dynamic object
var minus = {
doAction: function(){
console.log("this is minus");
}
}
var plus = {
doAction: function(){
console.log("this is plus");
}
}
var panelEvents = {
button: function(){
$(document).on("click", ".plus, .minus", function(){
var buttonClass = $(this).attr('class');
window[buttonClass][doAction](); //get an error
});
}
}
panelEvents.button();
Questions
1. How can I dynamically call various objects with the same methods?
2. Is it bad practice in point of OOP view to access methods in such way?
UPDATE
I understood, that it is not flexible approach. So now I have only theoretical interest of accessing dynamic object. Neither
window[buttonClass]['doAction']();
nor
window[buttonClass].doAction();
working.
Firebug:
TypeError: window[buttonClass] is undefined
window[buttonClass]'doAction';
Should I obviously attach minus and plus objects to window?
SOLUTION
The problem was that my code was inside jQuery object
$(document).ready(function(){
//my code
)};
With the line that fails, you are trying to call a function that is named the same as the content of the variable doAction. The problem here is that doAction is not defined.
You would have to write:
window[buttonClass]['doAction']();
or
window[buttonClass].doAction();
Sorry for the long winded title, but I think it summaries my problem
I have created a jsfiddle to cut down and create a simplified problem of my dilemma
http://jsfiddle.net/afw6k/3/
<input id="txtA"/>
<!-- after setupOnclick is executed my onlick for txtA should be onclick="someObj.log("Clicked!")"-->
<script>
function someObject(field){
this.field = field;
this.log = function(msg){
if(this.field.value != "") this.field.value += ", ";
this.field.value += msg
}
this.setupOnlick = function(){
field.onlick = function(){//So how do I pass this (as in someObject) to this?
this.log("Clicked!"); //As if I have written someObj.log("Clicked!");
}
}
}
var someObj = new someObject(document.getElementById("txtA"));
someObj.setupOnlick();
</script>
I'm not trying to simply write something to a textbox when clicked, but the above is a simplified version of what I am trying to accomplish here.
Passing this (the object) into an objects functions nested function
Or is there a far better way to accomplish this?
Save this in a variable:
this.setupOnlick = function(){
var theObj = this;
field.onlick = function(){//So how do I pass this (as in someObject) to this?
theObj.log("Clicked!"); //As if I have written someObj.log("Clicked!");
}
}
The value of this is just a value, so it can be copied to another variable. The variable "theObj" will remain in scope of the "click" handler when it runs.