What is this called in an Object literal? - javascript

so my question is when using an object literal inside a method I see people doing 'this.something = ...'
And then referencing it throughout their object. What's the name for this?
For e.g. Here in the example below if you look in the 'CacheDom' method 'this.button = document.getElementById('submit')' gives us a reference we can use later.
I understand the basics of the 'this' keyword and inside an object it will reference to that object, but I found it strange to be able to store elements etc and reference them later.
Essentially what is the official term for this?
Thanks
https://jsfiddle.net/rvs6ymqj/
HTML
<body>
<button id="submit" type="submit">Submit</button>
</body>
JS
var obj = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.button = document.getElementById('submit');
},
bindEvents: function() {
this.button.addEventListener("click", function() {
console.log("we clicked the button");
})
}
}
obj.init();

It varies from language to language. In Javascript, it's called a property. In Java, they're fields. C++ also calls them fields, though they may also be called data members.
JS is notably different from the other two in that Java and C++ force you to declare your fields, while JS members are defined on the fly. Really, JS objects are just maps from keys to values: the properties are the keys.

In Object-Oriented Programming, "this" refers to the object you are inside. You aren't storing properties in "this". It is a way to differentiate between global variables/constructor parameters and instance variables of the same name. I don't think there's a specific name for the concept of "this" but this phrase sums it up nicely:
'this' is usually an immutable reference or pointer which refers to the current object
https://en.wikipedia.org/wiki/This_(computer_programming)
Javascript-Specific Explanation:
JavaScript
When used outside any function, in global space, this refers to the
enclosing object, which in this case is the enclosing browser window,
the window object. When used in a function defined in the global
space, what the keyword this refers to depends on how the function is
called. When such a function is called directly (e.g. f(x)), this will
refer back to the global space in which the function is defined, and
in which other global functions and variables may exist as well (or in
strict mode, it is undefined). If a global function containing this is
called as part of the event handler of an element in the document
object, however, this will refer to the calling HTML element. When a
method is called using the new keyword (e.g. var c = new Thing()) then
within Thing this refers to the Thing object itself. When a function
is attached as a property of an object and called as a method of that
object (e.g. obj.f(x)), this will refer to the object that the
function is contained within. It is even possible to manually
specify this when calling a function, by using the .call() or .apply()
methods of the function object. For example, the method call
obj.f(x) could also be written as obj.f.call(obj, x). To work around
the different meaning of this in nested functions such as DOM event
handlers, it is a common idiom in JavaScript to save the this
reference of the calling object in a variable (commonly called that or
self), and then use the variable to refer to the calling object in
nested functions.

Related

What is difference between function FunctionName(){} and object.FunctionName = function(){}

Today while working my mind was stack at some point in javascript.
I want to know that what is basic difference between
function FunctionName(){
//Code goes here;
}
And
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
//Code goes here;
}
Both are working same. Then what is difference between then. Is there any advantage to use function with object name?
I have read Question. But it uses variable and assign function specific variable. I want to create object and assign multiple function in single object.
The first one defines a global function name. If you load two libraries, and they both try to define FunctionName, they'll conflict with each other. You'll only get the one that was defined last.
The second one just has a single global variable, MyFuncCollection. All the functions are defined as properties within that variable. So if you have two collections that try to define the same function name, one will be FuncCollection1.FunctionName, the other will be FuncCollection2.FunctionName, and there won't be any conflict.
The only conflict would be if two collections both tried to use the same name for the collection itself, which is less likely. But this isn't totally unheard of: there are a few libraries that try to use $ as their main identifier. jQuery is the most prominent, and it provides jQuery.noConflict() to remove its $ binding and revert to the previous binding.
The short answer is, the method in object context uses the Parent Objects Context, while the "global" function has its own object context.
The long answer involves the general object-oriented approach of JavaScript, though everything in JavaScript is an object you may also create arrays with this Method.
I can't really tell you why, but in my experience the best function definition is neither of the top mentioned, but:
var myFunction = function(){};
It is possible to assign function to variables, and you may even write a definition like this:
MyObject.myMethod = function(){};
For further reading there are various online Textbooks which can give you more and deeper Information about this topic.
One main advantage I always find is cleaner code with less chance of overwriting functions. However it is much more than that.
Your scope changes completely inside the object. Consider the following code ::
Function:
function FunctionName(){
return this;
}
FunctionName()
Returns:
Window {top: Window, location: Location, document: document, window: Window, external: Object…}
Object:
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
return this;
}
MyFuncCollection.FunctionName()
Returns:
Object {}
This leads to some nice ability to daisy chain functions, amongst other things.
The first:
function functionName (){
//Code goes here;
}
Is a function declaration. It defines a function object in the context it's written in.
Notice: this doesn't have to be the global context and it doesn't say anything about the value of this inside it when it's invoked. More about scopes in JavaScript.
Second note: in most style guides functions are declared with a capitalized name only if it's a constructor.
The second:
var myFuncCollection = {};
myFuncCollection.functionName = function () {
//Code goes here;
};
notice: don't use the new Object() syntax, it's considered bad practice to use new with anything other then function constructors. Use the literal form instead (as above).
Is a simple assignment of a function expression to a property of an Object.
Again the same notice should be stated: this says nothing about the value of this when it's invoked.
this in JavaScript is given a value when the function object is invoked, see here for details.
Of course, placing a function on an Object help avoiding naming collisions with other variables/function declarations in the same context, but this could be a local context of a function, and not necessarily the global context.
Other then these differences, from the language point of view, there's no difference whatsoever about using a bunch of function declarations or an Object with bunch of methods on it.
From a design point of view, putting methods on an Object allows you to group and/or encapsulate logic to a specific object that should contain it. This is the part of the meaning of the Object Oriented Programming paradigm.
It's also good to do that when you wish to export or simply pass all these functions to another separate module.
And that's about it (:

Is it preferable to use "this" or "that" (where var that = this)?

I'm fairly new to JavaScript and I'm cleaning up some JavaScript code I downloaded. One of the inconsistencies in this code is mixed usage of both this and the local variable that that references it.
An example code snippet (private method within a jQuery UI widget):
_populateLists: function(options) {
//do stuff with this
var that = this;
options.each(function(index) {
//use both this AND that, they are different in this scope
});
//here this and that are the same thing
//I want to be consistent, is one preferable over the other?
},
In many places throughout the code, where the scope is such that this === that, there is mixed usage, even within the same line of code.
For the sake of readability and maintainability, is it preferable to use this or that?
Note: I realize a lot of these types of things depend on developer preference. But before I decide to rewrite the code to use one over the other, I'd like to understand any reasoning if/why one would be preferred over the other.
EDIT: In this script, I think the only reason this is being assigned to a local variable is so that it can be referred to from within the inner closure.
The reason that the value of this is commonly assigned to a local variable is so that you can close over that value and use it inside a nested function.
this is a special variable and somewhat different from normal local variables in that it is automatically set to the object upon which a function was called (if any); otherwise, the global object. However, this intrinsic value of this is somewhat muddied by jQuery's liberal use of call and apply, which allow the caller to specify the value of this.
In a nested function, this does not inherit the value of its parent's this in the same way it would inherit a parent's local variables through the scope chain.
Because of this, we have to stash the value of this in a local variable if we need it inside a nested function, such as the each callback in your example.
var a = { fn: function() {
// here, `this` is the object `a`
var x = this;
function b() {
// here, `this` is `window` because `b` is invoked with no context
// ...but we still have access to `x`, whose value would be `a`
}
b();
}};
a.fn(); // by invoking `fn` as a property of `a`, we implicitly set `fn`'s
// `this` to `a`.
// Compare to:
var f = a.fn;
f(); // we now invoke `fn` with no context, so its `this` will be `window`.
a.fn.call(window); // or by specifying context explicitly
Of course, when you're still in the parent scope, this will still equal that (or self or whatever). At first glance, it may seem like there's no difference between the two, but there is one important performance impact:
Minification. If you assign this to a local variable, all references to that variable can be reduced to one character. References to this cannot. Compare this minified output:
function a() {this.w=1;this.x=2;this.y=3;this.z=4;}
function b() {var t=this;t.w=1;t.x=2;t.y=3;t.z=4;}
With 4 references to this, you save bytes by using a variable. If you have to capture this for an inner function anyway, using the local variable instead of this in the outer function gets you savings even with a single reference.
There isn't any reason, other than the standard subjective rationales of consistency and meaningful variable names.
If you go to the trouble of assigning this to a local variable, it's probably a good idea to use it, especially if you've given the local variable a useful name:
$('body').on('click', '.something', function() {
var clicked = this;
// now "clicked" is the element clicked on
});
for a jQuery example, but it's the same issue regardless of library or in raw JavaScript. Personally I think "that" is a pretty weak variable name in almost all cases.
If the purpose of assigning this to a local variable is to achieve semantics, then it would make sense to use a semantic variable name and then use the variable rather than this.
But since the purpose of assigning this to a local variable in this scenario is to cache it for use in an inner function, I think it's more readable/semantic to continue to use this in the outer scope.
While that is not normally a very good variable name, I think the meaning remains clear in this scenario. In my mind, in the inner scope, that is to this as parent is to self.
And since this is a jQuery UI widget, I looked at the source of some of the standard widgets that 'ship' with jQuery UI. It seems to be a standard convention to use this throughout except when needing to refer to the this of the outer scope. In the latter case, this is cached in a variable named that. Even when the local variable exists, it's only used in the inner scope.
Example for clarity:
_populateLists: function(options) {
var that = this; //we'll need `this` within a closure later
//do some stuff with `this`
options.each(function(index) {
//do stuff with `this` AND `that`
//`that` is the `this` of the outer scope
});
//do some more stuff with `this`
},
If consistency is the goal, then it makes sense to follow the same convention used by standard jQuery UI widgets.
When assigning a variable to $(this) when using jQuery, it is preferable to use $this as it refers to a jQuery object ( $ ). It is commonly used when $(this) no longer refers to the parent object when in the scope of another function.
The variable name however does not matter and simply refers to the object assigned. We could use $this, $that, $obj, that, obj, button etc. as our variable name, however this in javascript is a reserved word referring to the object in the current scope so we cannot use this as the variable name. You cannot assign any type of value to this or $(this).
Example...
this = 'something'; // or
$(this) = 'something';
Both of the above statements will throw an exception.
An example using $this = $(this); is shown below
To change the html of a button with the id of "someButton" after a successful jQuery post...
$('#someButton').click(function() {
var data = $('form').serializeArray();
// some validation or something
$this = $(this);
// note the lack of the var command to
// globalize $this within the click function
$.post('somePage',data,function(html) {
$this.html(html);
// identical to $('#someButton').html(html);
});
});

"this" does not refer to the this-reference using prototype [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
Today I ran into a very odd problem using Javascript's prototype and the this reference.
Basically, I have two objects. One object makes use of a div element and makes is possible to register an onclick event on the div. The other object makes use of this functionality and registers the onclick event using the first object.
Here is the code:
My first object, which takes care of the div:
DivObject = function() {};
DivObject.prototype.setClickListener = function(clickListener){
document.getElementById("myDiv").onclick = function(e){
clickListener(e);
};
};
My second object uses this functionality:
MainObject = function(){
this.myString = "Teststring";
this.divObj = new DivObject();
this.divObj.setClickListener(this.handleClick);
};
MainObject.prototype.handleClick = function(e){
// do something with e
};
The problem is, that inside MainObject.prototype.handleClick, the this reference refers to the window object, not to the MainObject. So, console.log(this) inside this function logs [Object window].
You can see this behaviour on jsfiddle.
As a workaround, I use the setClickListener function as follows:
var thisRef = this;
this.divObj.setClickListener(function(e){
thisRef.handleClick(e);
});
Now, the this reference in my handleClick function refers to my MainObject (as I want it to be).
See this workaround on jsfiddle.
My questions are:
Why does the this reference one time refer to the window object and one time to the this reference of my object? Is it overridden somewhere? I always thought using this in my object I can be sure that it is really the this reference of my object? Is the workaround I am using now the way how this problem should be solved or are there any other, better way to handle this case?
Your questions:
Why does the this reference one time refer to the window object and one time to the this reference of my object?
Other than using bind, the value of a function's this is set by how the function is called. When you do:
this.divObj.setClickListener(this.handleClick);
you are assigning a function reference, so the function is called later without any qualification (i.e. it's called as just handleClick rather than this.handleClick). On entering the function, because its this isn't set by the call, it will default to the global (window) object, or in strict mode remain undefined.
Is it overridden somewhere?
No, the value of this is set on entering an execution context. You can't overwrite it or directly assign to it, you can only set it in the call (e.g. as a method of an object, using new, apply, call) or using bind (also, arrow functions adopt the this of their enclosing lexical execution context).
I always thought using this in my object I can be sure that it is really the this reference of my object?
At the point you make the assignment, this is what you expect. But you are assigning a reference to a funciotn, not calling the function, so its this isn't set at that moment but later when it's called.
Is the workaround I am using now the way how this problem should be solved or are there any other, better way to handle this case?
Your work around is fine (and a common fix), it creates a closure so may have minor memory consequences but nothing serious. For very old versions of IE it would create a memory leak due to the circular reference involving a DOM object, but that's fixed.
The bind solution is probably better from a clarity and perhaps maintenance viewpoint. Remember to include a "monkey patch" for browsers that don't have built–in support for bind.
Please post code on SO, there is no guarantee that code posted elsewhere will continue to be accessible. The work around code:
MainObject = function(){
this.myString = "Teststring";
this.divObj = new DivObject();
var thisRef = this;
this.divObj.setClickListener(function(e){
thisRef.handleClick(e);
});
};
You could fix this by using .bind():
this.divObj.setClickListener(this.handleClick.bind(this));
See the demo.

Why can't I use "this" inside the inner function?

I am new to JavaScript. I have the following script working,
var navRef = this.navigator;
function onSearch( templateName) {
navRef.onSearch();
}
but not the one below and I am trying to understand why? Any help is appreciated. (navigator is sent as an argument to this object).
function onSearch( templateName) {
this.navigator.onSearch();
}
'this' points to different objects in the two cases. In the first case 'this' most likely refers to the windows object that has navigator as a property. In the second case 'this', most likely, refers to whatever object invoked the function. It's hard to be exact since you didn't give the context. But this should be enough to understand what's going on.
You need to read up on javascript scopes. In the first example the 'this' is referencing the current scope (that has the navigator property). In your second example, the 'this' is actually referencing the current function scope it is in.
You might want to check out this article on the this keyword. Essentially, this is used within a function to refer to the context in which that function is executed. When the function in question is called as a method on an object, this refers to that object. When the function is called in the global scope and has no instance to refer to, this refers to the window object.
Javascript has lexical scope so variables (like your navRef) can be used inside inner functions
var navRef = this.navigator;
function onSearch(){
navRef.onShow();
}
the this "variable", however, is an evil exception. Each function gets its own this (and the value it has depends on how the function was called) so if you want to access an outer this (or one of its properties) you need to use an intermediate variable:
var that = this;
function onSearch(){
that.navigator.onSearch();
}

Need help / Creating Methods via prototype property

Please help me to understand below code. This is the script for drag and drop object. I am trying to explore it but struck at one thing.
URL for Reference (Complete Script)
I dont understand how this method creation work, like get x(), set x() etc. Is get and Set is predefined object? will it actually set object value or get specific value of object, like we have in date object.
Also there is one space between its declaration set x(), why?
I am new to java script, i really appreciate your help.
// position strings are "x,y" with no units
get x()
{
return parseInt(this._position.split(',')[0]);
},
set x(inX)
{
var comps = this._position.split(',');
comps[0] = inX;
this.position = comps.join(',');
},
get y()
{
return parseInt(this._position.split(',')[1]);
},
set y(inY)
{
var comps = this._position.split(',');
comps[1] = inY;
this.position = comps.join(',');
},
Let's start by calling the language 'JavaScript' not 'java script'; the language is standardized as Ecmascript.
Look up creation of methods in Ecmascript (JavaScript). The functions set(inX) and get() are methods be of some prototype - the clue is the this reference referencing the current instance. However, one should write function get(), and function set(inX) instead.
From Wikipedia:
Prototype-based
prototypes
JavaScript uses prototypes instead of classes for inheritance. It
is possible to simulate many class-based features with prototypes in
JavaScript. functions as object constructors
Functions double as object constructors along with their typical
role. Prefixing a function call with new creates a new object and
calls that function with its local this keyword bound to that object
for that invocation. The constructor's prototype property determines
the object used for the new object's internal prototype. JavaScript's
built-in constructors, such as Array, also have prototypes that can be
modified. functions as methods
Unlike many object-oriented languages, there is no distinction
between a function definition and a method definition. Rather, the
distinction occurs during function calling; a function can be called
as a method. When a function is called as a method of an object, the
function's local this keyword is bound to that object for that
invocation.

Categories