Preserving a reference to “this” in JavaScript prototype functions [duplicate]

For preserving the context, the bind method is really useful, it’s now part of the recently released ECMAScript 5th Edition Specification, the implementation of this function is simple (only 8 lines long): // The .bind method from Prototype.js if (!Function.prototype.bind) { // check if native implementation available Function.prototype.bind = function(){ var fn = this, args … Read more

What does the variable $this mean in PHP?

It’s a reference to the current object, it’s most commonly used in object oriented code. Reference: http://www.php.net/manual/en/language.oop5.basic.php Primer: http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html Example: <?php class Person { public $name; function __construct( $name ) { $this->name = $name; } }; $jack = new Person(‘Jack’); echo $jack->name; This stores the ‘Jack’ string as a property of the object created.

Difference between getContext() , getApplicationContext() , getBaseContext() and “this”

View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity. Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just … Read more

What does ‘var that = this;’ mean in JavaScript?

I’m going to begin this answer with an illustration: var colours = [‘red’, ‘green’, ‘blue’]; document.getElementById(‘element’).addEventListener(‘click’, function() { // this is a reference to the element clicked on var that = this; colours.forEach(function() { // this is undefined // that is a reference to the element clicked on }); }); My answer originally demonstrated this … Read more

Pass correct “this” context to setTimeout callback?

EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout function call is made, because setTimeout executes the function with this pointing to the global object: var that = this; if (this.options.destroyOnHide) { setTimeout(function(){ that.tip.destroy() … Read more