FAQ Database Discussion Community


Java inheritance confusion, superclass and subclass member variable having same name

java,inheritance,this
On running this code class c1 { int ci = 1; } class c2 extends c1 { int ci = 2; } class inheritanceTest { public static void main(String args[]) { c1 c1reftoc2 = new c2(); System.out.println(c1reftoc2.ci); } } Output is 1. So i guess that a subclass object with...

Setting values with “this” keyword

java,this
Here is the program : class Vector3 { float x, y; public Vector3() { } public Vector3 (float x, float y) { this.x = x; this.y = y; } public Vector3 add(float x , float y) { return this; } public static void main(String args[]) { float delT = 0.2f;...

TypeScript: Lambdas and using 'this'

lambda,typescript,this
JavaScript frameworks often call callbacks using apply(). TypeScript's arrow notation, however, doesn't seem to allow me to access the 'this' pointer. How's it done? If it isn't, is there a place to down-vote the current 'this' handling on Lambdas?...

understanding of multiple inheritance for c++

c++,this,multiple-inheritance,virtual-functions,vtable
I'm reading multiple inheritance for c++ An Example in the paper:(page 377) class A {virtual void f();}; class B {virtual void f(); virtual void g();}; class C: A, B {void f();}; A* pa = new C; B* pb = new C; C* pc = new C; pa->f(); pb->f(); pc->f(); pc->g()...

Where can I get a better understanding of the overall and indepth understanding of instantiation with Context parameters?

java,android,sqlite,this,android-context
I am trying to resolve the connection between Context and Classes in this code and my understanding of this concept. The MainActivity.this does not work here. It came with the surrounding code. package com.Table; import android.content.Context; import android.graphics.Color; import android.os.AsyncTask; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.RelativeLayout;...

Timeout with bind, call & apply methods

javascript,closures,this,settimeout,iife
Up until now, I've always used var self = this before creating a function that would need access to its parent. However the bind() method seems like a more appropriate way to do so and I'm exploring that option, along with the apply() and call() methods. This is what I...

Using $(this) at a method inside another method in jQuery

javascript,jquery,this,each,selector
So, I'm trying to use the 'this' selector in a method inside another method, example: $('form').submit(function(event){ $('input').each(function(){ if($(this).val().length < 2){ $(this).addClass('error'); event.preventDefault(); } }); }); When I made that, I thought it would admit 'this' as each input, but no, the 'this' selector are associated to the form. I know...

Angularjs Apply toggle function to only the clicked button inside ng-repeat

javascript,angularjs,angularjs-ng-repeat,this,togglebutton
I created this fiddle exclusively to adress my problem. I am ng-repeating certain section. I have a toggle functionality to be implemented inside it. However, when I click the button, function gets triggered for all the repeated items. This works fine when not using ng-repeat inspite of using the same...

Passing “this” as a Method Argument - Clarification

java,swing,methods,this,actionlistener
I am currently working on Java Swing lessons after finishing my first set of lessons in Java. In this lesson, we are working on communication between different components (buttons,toolbars,etc.) that we have been studying. The problem is, "this" is being passed as a method argument for the addActionListener() method. This...

Trying to reference “this” referencing to a current string object. Not sure if I'm doing this right

java,class,object,this
Scenario quiz problem, final exam tomorrow and this problem makes NO sense to me, someone please please please show me the code segment that would fit the criteria. everything I try has failed. my biggest problem is I have no idea how to reference "this". So I have no idea...

Accessing “this” in asynchronous callback function in JavaScript

javascript,asynchronous,callback,this,setinterval
How would I achieve to reference the parent's "this" from inside an asynchronous callback function like in the snippet below? var imaginaryAjaxCall = function (fn) { setInterval(fn, 1000); } function parent() { this.foobar = "foo"; imaginaryAjaxCall(function() { this.foobar = "bar"; }); } Here's a jsfiddle for testing: http://jsfiddle.net/r0ueon53/11/ Edit: I...

Javascript this point to last object instance

javascript,object,this,instance
Before all, sorry for my bad english. I'm having problem with the context of a jquery Plugin i'm developing. Each instance I make of the plugin below, this points to last object. Example: var a = $("#a").EscribirConAdjuntos(); var b = $("#b").EscribirConAdjuntos(); var c = $("#c").EscribirConAdjuntos(); It results that a and...

How can I get rid of the `this` keyword in local functions?

javascript,this
I'm writing a small JavaScript game framework and often use objects' properties, like this.depth = this.y; But these this'es are quite annoying @_@. Is there a way to write just… depth = y; …not affecting global object? My instances are created via two factory functions, and they make a limited...

Returning `this` in a super method of inherited class

java,inheritance,polymorphism,this
let's say i have class A and class B which extends A, here are the classes: A: public class A { public int x; public static int y; public A(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public static...

JavaScript “this” context in .replace callback

javascript,callback,this
Consider the following very simplified example: var some_module = { func_a: function() { return 'a'; }, func_b: function(character) { if (character == 'b') { console.log(this); //refers to window return this.func_a; } else { return 'X'; } }, func_c: function() { console.log(this); //refers to some_module return "abcdefgh".replace(/[abc]/g, this.func_b); } }; some_module.func_c();...

Emergency: “error: non-static variable this cannot be referenced from a static context” [duplicate]

java,static,this,non-static
This question already has an answer here: non-static variable cannot be referenced from a static context 10 answers I have 4 hours to complete my exercise but I get multiple "cannot be referenced from a static context" errors. Here are these in full: MainApp.java:281: error: non-static variable this cannot...

Usage of this keyword inside parameter c# [duplicate]

c#,this
This question already has an answer here: Use of “this” keyword in formal parameters for static methods in C# 5 answers I have a class: public static class PictureBoxExtensions { public static Point ToCartesian(this PictureBox box, Point p) { return new Point(p.X, p.Y - box.Height); } public static Point...

Retrieve value from input next to a button using THIS selector

javascript,jquery,button,input,this
I ran into this problem, I have two siblings, an input and a button which calls a function to retrieve the value in the input, but it keeps telling me that Value is Undefined... Here's the "form": <li> <input id="mem3" value="TestU4" disabled=""> <button id="del3" class="delmem" onclick="deleteBandMember();">remove</button> </li> Here's jQuery Code:...

How to use “this” keyword to invoke multiple constructs with more than 1 arguments in the class?

java,constructor,this
I was studying this() keyword to invoke the constructors. I am pretty sure about its simple mechanism which is used to invoke the current class's other constructor: public class AsCaller { String name; int id; AsCaller() { System.out.println("No arguments"); } AsCaller(String n, int i) { this(); name = n; id...

Give “x” on this.x a variable value when passing objects to an array

javascript,jquery,this,variable-scope
I have seen in multiple questions on Stackoverflow, that I can pass a variable to a this keyword: name = "world"; alert("Hello " + this.name); However, I am struggling with the following code: $('.test').click(function() { var data = $(this).data(); var type = data.type; $('#world-map-geo1').empty(); $.getJSON('json/geoCountries-' + site + '.json', function...

read a part of variable $this

php,arrays,magento,this
I try to debug a function in Magento, I have a very big and complexe variable $this, inside I find the data I need but I can't read that I search the data in the part named "html" $html=$this->*Mage_Core_Block_Abstract*_transportObject['_data["html"]']; the first problem the * in the name are not reconized....

Is it possible to apply the same context to many functions?

javascript,call,this
Is there a way to bind the same 'this' context to different functions? var obj = {'a':1, 'b':2 }; init.call(obj); function init() { func1.call(this); func2.call(this); func3.call(this); etc... } Preferred syntax: function init() { // each function should use this. func1(); func2(); func3(); etc... } Not really a problem per se,...

What does the 'this' point to in prototype method?

javascript,prototype,this
The question confuses me for a time. Here's a simple code: function A() {}; A.prototype.B=function() {return this}; A.prototype.B(); The result in chrome console is: A{}; >B: function() {}; >constructor: function A() {}; > proto: Object As I know, 'this' point to the object who called the method. So I think...

Why does the “this” keyword refer to the subclass too?

java,oop,this
In the following scenario, Main.registerEvents(Listener) is part of an event system of a game API. Let's say it should register any method with the @EventHandler annotation. public abstract class Spell implements Listener { protected Spell() { Main.getInstance().registerEvents(this); } @EventHandler public void onMove(PlayerMoveEvent event) { } } public class Fireball extends...

ontouchlistener code cant be applied on int

android,this,ontouchlistener
i build an android application on android studio, and i put if statement on the command ontouchlistener code, and show message problem on "this", i think because it need int not intent ?! so i need to solve it please :) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); logpassj =...

Using HTML5 Audio in Javascript Objects

javascript,html5,this
When I run the following... var obj = { array: ['1.mp3', '2.mp3', '3.mp3'], audio: new Audio(this.array[0]) }; ...I get an error saying that it cannot read property '0' of undefined. However, when I run the following... var obj = { array: ['1.mp3', '2.mp3', '3.mp3'], }; var audio = new Audio(this.obj.array[0]);...

$(this) selector works in jsfiddle but not on my script [closed]

jquery,this,argument-passing,replacewith
See jsfiddle example... http://jsfiddle.net/nnmEY/21/ Objective... Modify textarea via the select menu and or via direct input and have the textarea value passed on to the div. Issues... 1.) The script at the very bottom of the example below works fine in jsfiddle but not in the example. 2.) I'm also...

How do I use $(this) in a jQuery hover event handler?

javascript,jquery,this
I have hidden an unordered list within a div. The div has a class '.feed-label' and I'm currently showing the ul when the div is hovered over. My problem is that when hovered over, all the other elements are also showing and I want only the one which was hovered...

What does 'this' mean in a c# constructor? [duplicate]

c#,constructor,this
This question already has an answer here: what is 'this' constructor, what is it for 4 answers I am very new to c# and I am working through a textbook. The textbook shows this piece of code: public class BankAccount { // Bank accounts start at 1000 and increase...

Uncaught TypeError: Cannot set property 'getV' of undefined

javascript,function,this
I have this function in javascript: function test(obj,arg1,arg2) { ... ... this.getV=function() { var x=2; return x; } } How can i resolve this problem ?...

jQuery: this: “$(this).next().next()” works, but “$(this).next('.div')” does Not

javascript,jquery,this,next
Okay, I am trying to get this set of information to hide individually. <img class="arrow" src="images/navigation/arrowright.png"> <H2>More Information</H2> <div class="box"> <h2>Bibendum Magna Lorem</h2> <p>Cras mattis consectetur purus sit amet fermentum.</p> </div> <img class="arrow" src="images/navigation/arrowright.png"> <H2>A Second Group of Information</H2> <div class="box"> <h2>Bibendum Magna Lorem</h2> <p>Cras mattis consectetur purus sit...

Using the this keyword with jQuery selectors

jquery,jquery-selectors,this
Can someone please help me with the syntax of using the jQuery this keyword? Here is my code that works: var obj = jQuery.parseJSON(data); $('.example_infobox1').addClass(obj.gridlayout); $('.example_infobox1 .info-box').addClass(obj.boxcolor); $('.example_infobox1 .info-box-icon').addClass(obj.iconcolor); $('.example_infobox1 i').addClass(obj.icon); $('.example_infobox1 .info-box-text').html(obj.text); $('.example_infobox1 .info-box-number').html(obj.number); Here is the code that I am working on: var obj = jQuery.parseJSON(data);...

Wordpress archive - how to handle just one element of a class for jquery animation?

jquery,wordpress,this
I have a simple animated corner on wordpress site. This works fine on front-page but on an archive page same animation happens on all elements not just current. The code is: //animacja zagiętych rogów $(".pad-fix", this).hover(function() { console.log('ok'); $(this).find('.hand').animate({ borderWidth: "12.5px" }, 400); $(this).find('.wiecej').animate({ right: "27px" }, 400); }, function()...

static variables within javascript functions and how it works under the hood

javascript,function,class,this
I'm having real trouble getting my head around some fundamental concepts in JavaScript so am hoping someone can give me a good explanation of what is happening under the hood in these examples. CASE 1: In this case I use the 'this' keyword in a constructor function: function Counter() {...

change label css class for checkbox if checked

javascript,jquery,css,checkbox,this
I have checkboxes that are hidden. I have images as the labels for the checkboxes, so that when the images are clicked the checkboxes are clicked. I am trying to make it so that the image has different opacities depending on whether the box is checked or not. Here is...

Using PHP and Laravel, why can i not append a variable to a value in an array?

php,class,oop,laravel,this
I am using the Listing Model to create rules for validation and I am trying to add the date() function to the value for one of the array's key/value pairs: class Listing extends Way\Database\Model { public $today_date; public function __construct() { $this->today_date = date("n/j/Y"); } protected $guarded = ['id','created_at','updated_at']; protected...

“this” (object) is undefined when calling angularjs function with $timeout

angularjs,service,this
I have an angular service to manage my on screen alerts: angular.module('theapp') .factory('Alerts', function ($timeout) { var unsetMsg = null; return { alertType: null, alertTitle: null, alertMessage: null, setMessage: function(type, title, message, timed) { var self = this; $timeout.cancel(unsetMsg); self.alertType = type; self.alertTitle = title; self.alertMessage = message; if (timed)...

This inside $(this)

javascript,jquery,this
I have encountered the following problem: function Conclude (thing){ this.quant = thing.find('#quantity_material').val(); this.thing = thing; this.material =[]; this.finish = []; this.make = function (){ var i=0; this.thing.each(function(){ this.material [i]= $(this).find('#material_val').val(); //Conclude.material doesn't work either i++; }); } } I want to assign conclude.material the values of an input out of...

Reference to Object.prototype.toString.call resulting in 'TypeError: undefined is not a function'

javascript,reference,prototype,this,typeerror
I'm encountering an unusual situation. I store a reference to Object.prototype.toString.call, in an attempt to make a shortcut, calling it as the assigned variable results in a TypeError, whereas calling it directly each time does not. Can anyone explain what is actually happening, as opposed to what I believe I...

how to economize jquery selectors

javascript,jquery,this,selector
Probably a stupid question, but I couldn't find a direct answer, so how can I change ":not('#home div, .nav')" in to something like ":not('this div, .nav')"? That would allow me reuse the same function for different objects. $( "#home" ).click(function() { $("#content .plates").children(":not('#home div, .nav')" ).fadeOut(700); }); and here is...

how to find refered object in a jquery function

javascript,jquery,function,this
how can i get this.V2 out of the FN scope !? $.fn.myFN = function(X){ this.V1 = X; this.V2 = X+2; }; $("#foo1").myFN(10); $("#foo2").myFN(20); console.log( $("#foo2").V2 ) // this returned undefined ...

AddEventListener with in a object

javascript,html,this,addeventlistener
I could need your help, at the moment I am trying to call a method within a object through a addEventListener activation. The problem is that the this pointer is changing as soon as the method get called. I tried to use the .call to give the method the right...

How do I target a “this” that is outside of its respective function?

javascript,jquery,this
Sorry if that title is confusing. Basically, I had to rewrite my code to implement the history api. Below is the before and after. You can see how before, the this keywords worked fine relative to .post-link. However, in the after, the this keywords don't work anymore since there is...

Unable to access “this” inside an object litteral

javascript,object,this,object-literal
I'm having a hard time understanding how I could access a this located inside one of the methods of an object literal I created. Here is an example: var app = { click: function(e) { e.preventDefault(); console.log('Clicked'); this.saywhat(); }, saywhat: function() { console.log('Say what ?'); } }; var link =...

passing a static method to another activity

java,android,this
I have a settings section in my android application, where the user using radio buttons, is able to change the main activity's background image. The problem is that when I turn the method for storing the selection of the user into static, I can not use this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);to read the...

Angular: How to get an input value using $this

javascript,angularjs,this,keyup
I am hoping to get an input value inside a keyup function that can runs from multiple inputs. Every time there is a keyup the function will trigger according to the specific input. So, I am trying to use $this inside the function. No succes so far.. HTML code: <input...

Check for empty form fields in this field only

jquery,forms,validation,this
I have this code: $("form").submit(function() { $(":input").each(function() { if($(this).val() === "") alert("Empty Fields!!"); }); }); It works great but when I have more than one form on a page, it checks all forms. I wan't to check only the submitted form using the "this" selector. How shall I implement the...

Bind 'this' variable from javascript 'String' function to another addon function

javascript,string,this,bind
I am trying to bind this function var addon = function(a){ if (typeof a == "string"){ return this+a; }else{ return this+String(a||""); } } To String.prototype.addon So that when I call "I".addon(" remember."); It returns "I remember." This is what I have for the String.prototype.addon so far. String.prototype.addon = addon.bind(); I...

jQuery 'this' following a .find click function

javascript,jquery,function,this,jquery-find
Need some help with this one...I have the following javascript code: var quickSection = $('.quick-links'); var quickContent = $('.quick-links .row .inner-content') if ( quickSection.is('*') ) { quickContent.find("img").click(function() { $(this).find("ul").slideDown("slow"); }); } There are three instances of my variable quickContent. Each have a ul, img, etc. I need to display the...

how do i get “this = this” in prototype working

javascript,prototype,this,reverse
Ok peep's so I know it's bad practice to mess with prototypes but here it is anyway... Array.prototype.rev= function(){ this.reverse(); } Works fine! Updates the source array variable, ary, as expected eg: ary = [123, 456]; ary.rev(); // result: ary == [456, 123] My problem comes when writing a...

How to trigger 'this' within a loop in React

javascript,reactjs,this
I am kind-of new to react and having trouble getting value of a radio button generated from a loop. I have a fiddle set-up at: https://jsfiddle.net/rexonms/zrax0zfa/. The example has two type of radio buttons. One group is generated using loop and the other one without loop. The one without loop...

In angular is it possible to move a $scope property to controller scope?

angularjs,scope,this
I'm now creating a nested controller, with the parent controller passing a variable in, like this: app.directive('entity', function() { return { restrict: 'E', controller: 'EntityShowController', templateUrl: '/show.html', controllerAs: 'showCtrl', scope: { entity: '=' // two way binding parent/child } }; }) And in the template I have: <entity entity="parent.getSelected()"></entity> Now...

Accessing non static members inside static method via passed pointer

c++,multithreading,static,this
Not the actual code, but a representation: I need to initiate a thread from one of my member functions and I do that this way: return_val = pthread_create(&myThread, NULL, myStaticMethod, (void*)(this)); i) I pass this as an argument because static methods do not allow non-static members to be accessed, and...

Should there by a [dojo] hitch in my giddy-up?

javascript,dojo,scope,this
I'm using working on some custom Dojo widgets but keep feeling like I'm the proverbial contortionist that scratches their ear by reaching twice around their head. For some reason my use of dojo.hitch() doesn't feel right. Here's what works: myObject = { one: function() { promise = new Deferred(); promise.then(dojo.hitch(this,...

Storing this object in custom private variable

javascript,jquery,this,global
I have this js object var toggleItem = { attrData : '', toggleNew : '', toggleOld : '', //var self : this, init : function(){ self = this; self.listener(); }, listener : function(){ jQuery('.btn-save').click(function(){ var current = this.id.split('_').pop(); self.toggleNew = jQuery('.toggle-data-new_'+current).val(); self.toggleOld = jQuery('.toggle-data-old_'+current).val(); self.updateForm(); }); }, updateForm : function(){...

c++ map container [this] () [duplicate]

c++,dictionary,this,containers
This question already has an answer here: Strange use of [] in C++. What is happening? [duplicate] 2 answers I am learning to use map containers, and I can see the logic, we can define the key and the value when we insert any object. I also know that...

$(this) only working for one item [jQuery]

javascript,jquery,html,css,this
I am using $(this) to get the css attribute of an HTML element, but it is only working for one of them. The items are the same, except all but the one that is working are being positioned relatively. Here is my HTML: <div class="red" id="color"></div> <div class="orange" id="color"></div> <div...

Is it possible to use $(this) in a function called from another function?

jquery,function,this
Sorry for the question title, I know it's not very well worded, but I couldn't really explain what I'm asking in a summary. I have a JQuery function tied to the click event of an element. For reasons that may well be flawed (other than making more sense to me...

how to select all elements with matching attribute of this in jQuery?

javascript,jquery,html,attributes,this
I would like to select all elements within a div that have the same attribute as the selected element, using the this selector. So in my example, when I click on an element with a class of .foo, I would like to find all elements within .container that share the...

Why is self-referencing pointer or this out of scope in button?

java,swing,this,self-reference,state-pattern
I'm trying to produce a dynamic canvas using the Swing library with the State pattern. My code can compile but with red marks all over the console when my buttons are pressed. The problem: my self-referencing pointer or reserved word this is out of scope in button. I want to...

Issue passing 'this' into Javascript function

javascript,this
Slightly confused by this problem. I have written this function to replace punctuation in input elements: function punctuationReplace(element){ var elementToChange = document.getElementById(element); elementToChange.value = elementToChange.value.replace(/\"/g, ''); elementToChange.value = elementToChange.value.replace(/\'/g, ''); elementToChange.value = elementToChange.value.replace(/&/g, 'and'); elementToChange.value = elementToChange.value.replace(/</g, ''); elementToChange.value = elementToChange.value.replace(/>/g, ''); }...

javascript 'this' code for chaining

javascript,methods,this
I am trying to develop a library like jQuery that allows chaining. I already have functions that work, but I need to chain them together. Please review the code below and assist me with solving how I can use 'this' to access the right context and develop a jQuery-like library...

trying to extract a string from a js this keyword

javascript,search,this
I'm trying to execute javascript after a link is clicked before loading the link, using this code: $('body').on("click", 'a', function (evt) { evt.preventDefault(); console.log(this); $('.content').addClass('hide'); if (this.search("AV") > 0) { $('#AVheader').addClass('fullwidth'); } setTimeout(function () { window.open(this, "_self"); }, 500); }); My errors are: this.search Isn't a function and window.open(this, "_self");...

Using prototype apply vs this to call function

javascript,prototype,this
On the MDN String page they have an example to polyfill String.includes. String.prototype.includes = function() {'use strict'; return String.prototype.indexOf.apply(this, arguments) !== -1; }; Is there a reason they used String.prototype.indexOf.apply vs calling indexOf directly on this? String.prototype.includes = function(searchString, position) {'use strict'; return this.indexOf(searchString, position) !== -1; }; ...

Can “this” be used in place of a selector? …in jQuery?

javascript,jquery,this
I'm learning JavaScript and JQuery, and trying to wrap my head around "this." Is $("p").click(function(){ $("p").slideUp('slow');}); functionally, the same as $("p").click(function(){ $(this).slideUp('slow');}); ? I'm sure there are more clever ways to use "this", but if I'm right that it is functionally the same, then I know I have a little...

How iterate through two array in a object using Template helpers in Meteor.js

javascript,json,meteor,handlebars.js,this
My HTML resembles this <template name="stop"> {{#each thumb}} <tr> <td class="image" ><img src="{{this.data}}"></td> <td> <center style="float:right; margin-bottom: 25%;"> <h2> Do you like this product? </h2> <h2>{{this.text}}</h2></center> </td> </tr> {{/each}} </template> And this template refers to my template helper which look like this Template.stop.helpers( { 'thumb': function(data) { console.log(z); return tweetImages.findOne()...

what does the keyword this does in the code and are there any alternate methods without this keyword? [duplicate]

java,this
This question already has an answer here: What does “this” mean? [duplicate] 6 answers in the class Student here what does the keyword this used in the functions refer to? what does it return exactly? is it only used in java or c/c++ also? is there any difference if...

Consolidate validation function

jquery,forms,validation,this
Hi trying to consolidate this validation function that checks 3 age inputs. At the moment it highlights the incorrect input and shows/hides an error message if the age is under 18. How would I make the function run on all 3 inputs and stop repeating myself? //Adult age validation validateAdultAge0:...

jQuery getting ID of input with class on keyup not working

javascript,jquery,input,this,keyup
I have a bit of problem with my code here. What I am trying to accomplish is to get the ID of an input field on key up. All the input fields of interest have a class "count". All of them also have the same ID but it increments, say...

Jquery Ajax callback doesn't recognize $(this) object [duplicate]

javascript,jquery,ajax,callback,this
This question already has an answer here: Passing $(this) to a callback in jQuery? 3 answers It it my code $(".library-fields-container div.field-content img").click(function(){ var nid = getImageNodeID($(this).siblings(".image-span").text()); $.ajax({ url: Drupal.settings.basePath + 'views/ajax', type: 'POST', dataType: 'json', data: 'view_name=fehrest&view_display_id=block_1&view_args='+nid, success: function(response) { var output = response[1].data; alert(output); $(this).hide(); }, error:...

How does “this” work in functions that are assigned in the constructor?

javascript,function,constructor,this
I found this example code: function personFullName() { return this.first + ' ' + this.last; } function Person(first, last) { this.first = first; this.last = last; this.fullName = personFullName; } var dude = new Person("Michael", "Jackson"); alert(dude.fullName()); Which alerts "Michael Jackson". I changed it to call personFullName from the constructor...

Select one (this) item from
  • (jQuery/javascript)
  • javascript,jquery,html,html-lists,this
    I have a <ul> list in my HTML, and inside each <li> within that, I have an element with the id vid. With jQuery, I want to make it so that when I click the title of each <li>, the #vid element in that <li> (just the one that was...

    JS: this reference does not work [duplicate]

    javascript,jquery,this,argument-passing
    This question is an exact duplicate of: Using this in event handler in strict javascript? 3 answers I want to encapsulate my Javascript code for certain objects in structures as indicated below. However, I ran into trouble with the semantics of this. While this during tiles.init() refers to the...

    std::enable_shared_from_this: no known conversion from a to a

    c++,c++11,this,shared-ptr
    I have a class VectorSpace with a member createVector() which creates a Vector with a shared pointer to the referencing VectorSpace. This is achieved by std::enable_shared_from_this. However, this following code #include <memory> class Vector; class VectorSpace; class Vector { public: Vector(std::shared_ptr<VectorSpace> & space): space_(space) { }; private: std::shared_ptr<VectorSpace> space_; };...

    How to change parent state from child component?

    javascript,reactjs,this
    I'm learning react.js and try to do something like this: I have NumberBox component with NumberLink child components. NumberBox has val state. NumberLink has val property. When I click NumberLink I'd like to change NumberBox state to link's val property, but in console I get: Uncaught TypeError: this.props.onNumberLinkClick is not...

    When should I use const& to this?

    c++,reference,const,this
    I found some code like this: class foo{ int a; public: foo(int v) : a{v} {} bool operator==(const foo& rhs) const&{ return (rhs.a == a); } }; It compiles and runs. I was wondering what are the benefits (or drawbacks) of having the reference (&) to this in the operator==....

    Passing this pointer to a templated member variable

    c++,this
    #include <iostream> using namespace std; template<class C> class Bar { public: Bar(C& c) : _c(c) {}; ~Bar(){}; private: C& _c; }; class Foo { public: Foo() : bar(this) {}; //instead of bar(*this) ~Foo(){}; private: Bar<Foo> bar; }; int main() { // your code goes here Foo f; return 0; }...

    Can I access properties of a scope object within itself using “this”?

    javascript,angularjs,object,scope,this
    I need to get the total of the following example: $scope.fees = { basic: 1, premium: 2, total: this.basic + this.premium } Why won't this work? It says this is undefined. Is there a way to achieve this without having to write out total: $scope.fees.basic + $scope.fees.premium. I'd love if...

    Arrow Functions and This

    javascript,this,ecmascript-6,arrow-functions
    I'm trying out ES6 and want to include a property inside my function like so var person = { name: "jason", shout: () => console.log("my name is ", this.name) } person.shout() // Should print out my name is jason However, when I run this code console only logs my name...

    How To Make My Code Less Verbose

    jquery,wordpress,this
    I am using jQuery in Wordpress and it is doing exactly what I expect it to do. The problem is that I had to re-write the function I am using 4 times (currently, may be even more later) for the SAME operation. I know that there must be a way...

    Binding Object Prototype Functions to Object in Javascript

    javascript,prototype,call,this,bind
    Background I have a prototype object that has dozens of functions that access info from a list like this: var prototype_object = { yellow: function(list) { return list[this.type+'_yellow']; }, green: function(list) { return list[this.type+'_green']; }, // ... 50 more functions here } The 'this.type' is supposed to come from the...

    How to reference a field from within an object

    javascript,this
    I'm trying to address a field of an object in javascript from within a function in another field like this: var binds = {}; var name = 'hi'; binds[name] = { foo: [], bar: { add: function (e) { foo.push (e); } } } I tried this.foo.push (e) and binding...

    Is there a shortcut for typing this.x = x in java while constructing an object?

    java,this,shortcut
    When I am storing a parameter (or is it an argument?) to a private instance variable of a class, is there is quicker way to write this.x = x (where x is the argument of the constructor and this.x is the instance variable)? Sometimes with longer variable names I find...

    How to evaluate custom javascript expression with the context in strict mode?

    javascript,properties,scope,this,eval
    Update I've come up with a concise solution to this problem, that behaves similar to node's vm module. var VM = function(o) { eval((function() { var src = ''; for (var prop in o) { if (o.hasOwnProperty(prop)) { src += 'var ' + prop + '=o[\'' + prop + '\'];';...

    How can this be undefined in the constructor of an Angular config class?

    angularjs,constructor,typescript,undefined,this
    I've found some examples online, where people create TypeScript config classes and pass them on to Angular. When I've tried it, I got the weird exception, that this was undefined. A closer look to the other implementations revealed, they only use the constructor, so, are those examples actually inherently wrong...

    I'm confused with the this keyword in javascript, I want to know if I can do what I intended?

    javascript,function,this
    This code works fine, although what I'm interested in knowing is, if there's a way that works better and is which I prefer better, which it seem to not be working. Is it possible to do it that way, check the second code example in order to comprehend, what I...

    Explanation to a certain java command

    java,class,printing,this
    System.out.println(((Window)this).size); Say we have a class Window and the above command is written inside a method in a subclass. I want some help understanding what (Window)this does exactly. Where it refers to....

    Error: 'this' object is incorrect; In JQuery click event - Unexpected Behavior on click

    javascript,jquery,html,ajax,this
    I have been trying to add a 'Cancel' button to some existing HTML and jQuery code that has some ajax calls. I have the 'Cancel' button working, however it stopped some of the behavior of my 'Edit' button. I cannot seem to figure out why the jQuery click event is...

    Why is “this” necessary when define arguments?

    javascript,this
    function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } var family = {}; family.mother = new Person("Susan", "Doyle", 32); … Do we have to use "this" here? and why? function … { firstName = firstName; lastName = lastName; age = age; } I wonder...

    local reference to this?

    javascript,this
    Why does 'this' need a local reference? The first code segment works fine but the second code segment thows an error... you're creating a reference (not being passed by value) so you would be modifying the same object prototype which is what you're trying to do anyways... not sure where...

    Angularjs $scope and this functions

    javascript,angularjs,scope,this
    I am working on a small application in angularjs :- I am working on deleting a contact. Everything works fine but the this.openModal() throws an error as undefined even though it is defined in the same JS. Have some confusions on how to use this and $scope together. Can anyone...

    How to reference JavaScript class via “this” within jQuery?

    javascript,jquery,reference,this,javascript-objects
    Consider the following JavaScript class, property, and method: function Foo() { this.data = 123; } Test.prototype.foo = function() { $("body").append($("<div>") .text("Hello World!") .click(function () { alert("Data: " + this.data); }) ); } var Bar = new Foo(); Bar.foo(); Why is the property data undefined in the alert box? How can...

    How do I gain the context I want when using a method from an object in a method of another object?

    javascript,this
    First Object and method: objectOne.prototype.getData = function (id, callback) { this._sendRestRequest({ method: "GET", path: /accounts/ + id + "/data" }, function (error, body, statusCode) { if (error) { if (body && body.message) { console.error("[ERROR]", statusCode + " Error: " + body.message + " (error code " + body.code + ")");...

    What does '$(this)' contains in a below javascript function code?

    javascript,jquery,function,this,alert
    Following is the code of a function : $Core.notification = { bDebug: false, update: function() { setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); }, setTitle: function() { var iTotal = 0; var sTitle = $('title').html(); $('.holder_notify_count').each(function(){ alert($(this)); iTotal += parseInt($(this).html()); }); var newTitle = ''; var aMatches = sTitle.match(/(\([0-9]*\))/i); if (aMatches !== null...

    How to assign $(this) with multiple same class vs unique id

    jquery,class,this
    I have asked a similar question in the past but I put together the following example that better illustrates the results i'm seeking. Using unique id with classic js.(it works) <style> #par {width:350px; background:#DDD; padding:5px;} #tatx {color:#C00;} </style> <div id="par"> Select an option, then, select another option<br> <select id="sl" onChange="sltota();tatotx()">...

    IntelliJ/Android Studio: remove unnecessary use of 'this.'

    java,android,intellij-idea,android-studio,this
    I am working on a project where previous developers added lots of this.x code which in my opinion makes it longer and thus less readable. And it was placed all over the project by some Eclipse save action. What I am looking for is an IntelliJ refactoring method that I...

    Javascript call method

    javascript,this
    Why the following code will output 1 ? function func(){ alert(this) } var i = 1; func.call(i); ...

    How does each function and this keyword work together in d3?[chaining transitions]

    javascript,d3.js,this,each
    I'm using the d3 library and having a hard time wrapping my head around some of the constructs, hoping for some guidance from experienced hands with this! <!DOCTYPE html> <html lang="en"> <head> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <script> var svg=d3.select("body").append("svg").attr("width",800).attr("height",1000); svg.selectAll("circle") .data(d3.range(10)).enter().append("circle") .attr("cx",function(d){return d;})...

    How to circumvent the ES6 Class scoping issue with 'this' key word [duplicate]

    javascript,socket.io,this,ecmascript-6
    This question already has an answer here: How to access the correct `this` / context inside a callback? 4 answers How do I write a named arrow function in ES6? 1 answer For example in the Class constructor: Socket.on('user:join', onUserJoin); 'onUserJoin' is declared as a method of the class...