Why is "this" needed to call functions inside an object - javascript

var a = {
text : 3,
logText : function () {
console.log(this.text);
},
callLogText : function() {
logText();
}
};
a.callLogText();
This will genernate a ReferenceError: logText is not defined error message.
Instead, you prefix this to the logText() method, it will be ok. No error msg will pop.
var a = {
text : 3,
logText : function () {
console.log(this.text);
},
callLogText : function() {
this.logText();
}
};
I really cant figure out the reason.

You need to learn the JavaScript scoping rules. This blog post gives a good introduction.
In a nutshell, JavaScript follows some rules when you use a variable name (for the purpose of this explanations, function definitions are pretty much like variable declarations).
What probably confuses you is this:
var a = { b: ...};
var a = function() { var b = ... }
In both cases, you get a new variable a. In the first case, it's an object with a property b. In the second case, it's a function which has a nested scope in which a new variable b is defined.
JavaScript will look in the current and all parent scopes for variables. But object definitions are no scopes. As far as JavaScript is concerned, the property b is invisible unless you make it visible by using the special variable this which always references the "current" object (in your example, that is a).
Since the properties of the object a are not "in scope", JavaScript can't find logText() unless you tell it to look in this. If you don't say anything, JavaScript will look in the current scope (the body of the function callLogText), then the parent scope (in which a is defined) and then in any parent scopes of that.

It's not a quirk. It's how most languages function when it comes to objects.
logText() is a method of the a object, not a function.
You need to call methods internally as this.methodName() or externally as object.methodName().

logText(); is to execute a global function logText which is undefined.
this.logText(); is to execute the function a.logText.

Calling
logText();
means somewhere there is a function named logText(), but here you have defined logText() as a property of an object, so to access the logText() you have to refer it with the help of the object it is defined in. In this case it is in the same object so you refer to the same object by saying this.

Related

Why doesnt javascript check object's local scope first?

Why doesnt the outer scope get accessed in the inner scope ?
I am coming from C++ world where any reference to an unqualified variable inside a class's method is attempted to be resolved first within the object's scope and then in the outer scope. And this happens without having to use "this" keyword.
For ex:
#include <iostream>
using namespace std;
std::string name = "Global::name";
class MyClass {
private:
string name = "MyClass::name";
public:
void printName() {
// No need to use 'this' keyword to refer to the variables in the
// object's scope, unless there is an ambiguity to resolve
cout << "Name from inside printName is: " << name << "\n";
}
};
int main()
{
MyClass obj;
cout << "Name from inside main is: " << name << "\n";
obj.printName();
return 0;
}
prints
Name from inside main is: Global::name
Name from inside printName is: MyClass::name
But in javascript, the following code snippet
function fn() {
let name1 = "fnB";
console.log("Inside fn() name is : ", name1);
}
var obj = {
name1: "objA",
objFn: function() {
console.log("Inside objFn() name is : ", name1); // ERROR !!
// console.log("Inside objFn() name is : ", this.name1); // OK !
}
}
fn();
obj.objFn();
results in
Uncaught ReferenceError: name1 is not defined
at Object.objFn (my.js:10)
What is the reason javascript doesnt want to refer to the "name1" variable in the scope of "obj" object, without requiring "this" keyword to refer to it ? What is the problem that is being solved by forcing the use of "this" keyword in this context ?
Every language is different and makes different tradeoffs. An obvious difference between C++ and JavaScript wrt class/object methods:
In JavaScript, every function is a standalone object. It doesn't strongly belong to anything.
In C++, class methods belongs the class. They cannot be invoked without it.
In JavaScript, every function is a closure, i.e. it has access to free variables defined in a "higher" lexical scope.
In C++, methods are not closures.
Why does this matter? Consider the following example:
var name = 42;
var obj = {
name: "objA",
objFn: function() {
console.log("Inside objFn() name is : ", name);
}
}
Which name should objFn access according to your expectation?
As it is now, the function would log 42, because that's how lexical scoping + closures work. In order to access the object's name property I have to write this.name.
Now lets assume it was the other way round, that object properties would be accessed before the outer scope. Then in order to explicitly access the outer scope's variables, i.e. 42, we would need some new API, e.g. getVariableFromScope('name'). This is worse than always requiring this for a simple reason: It makes it more difficult to reason about the code. By always requiring this, the rules are very simply:
Want to access a property on the object? this.<property>
Want to access a variable in scope? <variable>
In your case it would be:
Want to access a variable in scope? <variable>, but only if the object doesn't have a property with the same name, otherwise getVariableFromScope('<variable>').
Want to access a property on the object? <property>, but only if there is not a local variable with the same name, otherwise this.<property>.
One possible tradeoff here is consistency vs convenience.
Also consider the following example:
var foo = 42;
function bar() {
console.log(foo);
}
Calling bar() will log 42. Now lets assume I pass the function to some third-party code someOtherFunction(foo) which does:
function someOtherFunction(func) {
var obj = createObject();
obj.func = func;
obj.func();
}
Do you see the problem? The result of calling bar now depends on whether obj has a name property or not. To resolve this, either someOtherFunction needs to know which free variables bar contains or bar needs to know that someOtherFunction assigns it to some object and has to account for that. Either way, the code would be tightly coupled.
Doing what C++ or Java does would basically mean to introduce dynamic scope, and I assume there is a reason why very few languages use it.
(Someone might argue that this is also like dynamic scope. Well, this is a single keyword. It's easier to reason about that than to reason about the space of all possible variable names that could be overwritten.)
There are probably more reason why the behavior you are describing is not desirable in JavaScript. But again, programming language design is all about tradeoffs.
The this keyword behaves quite differently in javascript from how it does in many other languages. The value of this is not figured out until the function is invoked, and may not have anything to do with the object you think its associated with.
For example, consider the following code:
const obj = {
name: 'bob',
sayName: function () {
console.log(this.name);
}
}
const verbalize = obj.sayName; // Make another way to reference the function
console.log(verbalize === obj.sayName); // They're literally the same function
// And yet they log very different things
obj.sayName(); // logs 'bob'
verbalize(); // for me, it logs 1d7dcb5e-0fde-4726-8875-4bdcd636c6eb
Why does verbalize produce such a weird result? Well, since i'm invoking the function without specifying what this should be equal to, this defaults to the global window object, and so i end up logging window.name, which for me happens to be "1d7dcb5e-0fde-4726-8875-4bdcd636c6eb".
So if the language was set up to check this before checking other scopes, the actual result would be (in some cases) to check for global variables before local variables, which is the exact opposite of what we'd like to happen. Thus, this has to be done explicitly.
(ps: while this can be set to the window object in some cases, it can also be set to undefined if you're in strict mode)

Can you get the property name through which a function was called?

I've done a lot of searching and some playing around, and I'm pretty sure the answer to this question is no, but I'm hoping a JavaScript expert might have a trick up his sleeve that can do this.
A JavaScript function can be referenced by multiple properties, even on completely different objects, so there's no such thing as the object or property that holds the function. But any time you actually call a function, you must have done so via a single object (at the very least, the window object for global function calls) and property on that object.
(A function can also be called via a function-local variable, but we can consider the function-local variable to be a property of the activation object of the scope, so that case is not an exception to this rule.)
My question is, is there a way to get that property name that was used to call the function, from inside the function body? I don't want to pass in the property name as an argument, or closure around a variable in an enclosing scope, or store the name as a separate property on the object that holds the function reference and have the function access that name property on the this object.
Here's an example of what I want to do:
var callName1 = function() { var callName = /* some magic */; alert(callName); };
var obj1 = {'callName2':callName1, 'callName3':callName1 };
var obj2 = {'callName4':callName1, 'callName5':callName1 };
callName1(); // should alert 'callName1'
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'
From my searching, it looks like the closest you can get to the above is arguments.callee.name, but that won't work, because that only returns the name that was fixed to the function object when it was defined, and only if it was defined as a named function (which the function in my example is not).
I also considered that maybe you could iterate over all properties of the this object and test for equality with arguments.callee to find the property whose value is a reference to the function itself, but that won't work either (in the general case), because there could be multiple references to the function in the object's own (or inherited) property set, as in my example. (Also, that seems like it would be kind of an inefficient solution.)
Can this be done?
Short answer:
No, you cannot get "the property name" used to call your function.
There may be no name at all, or multiple names across different scopes, so "the property name" is pretty ill defined.
arguments.callee is deprecated and should not be used.
There exists no solution that does not use arguments or closure.
Long answer:
As thefourtheye commented, you should rethink what you are trying to do and ask that instead in a new question. But there are some common misconceptions, so I will try to explain why you cannot get the "simple property name".
The reason is because it is not simple.
Before we go ahead, let us clarify something. Activation Objects are not objects at all.
The ECMAScript 5.1 specification calls them Environment Records (10.2.1), but a more common term is Scope chain.
In a browser the global scope is (often) the window object, but all other scopes are not objects.
There may be an object that you use to call a function, and when you call a function you must be in some scope.
With few exceptions, scopes are not objects, and objects are not scopes.
Then, there are many names.
When you call a function, you need to reference it, such as through an object property. This reference may have a name.
Scope chain has declarations, which always have a name.
A Function (the real function, not reference) may also have a function name - your arguments.callee.name - which is fixed at declaration.
Not only are they different names, they are not (always) the "the property name" you are seeking.
var obj = { prop : function f(){} }, func = obj.prop;
// "obj" and "func" are declarations.
// Function name is "f" - use this name instead of arguments.callee
// Property name is "prop"
func(); // Reference name is "func"
obj.prop(); // Reference names are "obj" and "prop"
// But they are the same function!
// P.S. "this" in f is undefined (strict mode) or window (non-strict)
So, a function reference may comes from a binding (e.g. function declaration), an Object (arguments.callee), or a variable.
They are all References (8.7). And reference does have a name (so to speak).
The catch is, a function reference does not always come from an object or the scope chain, and its name is not always defined.
For example a common closure technique:
(function(i){ /* what is my name? */ })(i)
Even if the reference does have a name, a function call (11.2.3) does not pass the reference or its name to the function in any way.
Which keeps the JavaScript engine sane. Consider this example:
eval("(new Function('return function a(){}'))()")() // Calls function 'a'.
The final function call refers the eval function, which refers the result of a new global scope (in strict mode, anyway), which refers a function call statement, which refers a group, which refers an anonymous Function object, and which contains code that expresses and returns a function called 'a'.
If you want to get the "property name" from within a, which one should it get? "eval"? "Function"? "anonymous"? "a"? All of them?
Before you answer, consider complications such as function access across iframes, which has different globals as well as cross origin restriction, or interaction with native functions (Function.prototype.bind for example), and you will see how it quickly becomes hell.
This is also why arguments.caller, __caller__, and other similar techniques are now all deprecated.
The "property name" of a function is even more ill defined than the caller, almost unrealistic.
At least caller is always an execution context (not necessary a function).
So, not knowing what your real problem is, the best bet of getting the "property name" is using closure.
there is no reflection, but you can use function behavior to make adding your own fairly painless, and without resorting to try/catch, arguments.callee, Function.caller, or other strongly frowned-upon behavior, just wasteful looping:
// returning a function from inside a function always creates a new, unique function we can self-identify later:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//the one ugly about this is the extra "()" at the end:
var obj1 = {'callName2':callName(), 'callName3':callName() };
var obj2 = {'callName4':callName(), 'callName5':callName() };
//test out the tattle-tale function:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
if you REALLY want to make it look like an assignment and avoid the execution parens each time in the object literal, you can do this hacky routine to create an invoking alias:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//make an alias to execute a function each time it's used :
Object.defineProperty(window, 'callNamer', {get: function(){ return callName() }});
//use the alias to assign a tattle-tale function (look ma, no parens!):
var obj1 = {'callName2': callNamer, 'callName3': callNamer };
var obj2 = {'callName4': callNamer, 'callName5': callNamer };
//try it out:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
all that aside, you can probably accomplish what you need to do without all the looping required by this approach.
Advantages:
works on globals or object properties
requires no repetitive key/name passing
uses no proprietary or deprecated features
does not use arguments or closure
surrounding code executes faster (optimized) than
a try/catch version
is not confused by repeated uses
can handle new and deleted (renamed) properties
Caveats:
doesn't work on private vars, which have no property name
partially loops owner object each access
slower computation than a memorized property or code-time repetition
won't survive call/bind/apply
wont survive a setTimeout without bind() or a wrapper function
cannot easily be cloned
honestly, i think all the ways of accomplishing this task are "less than ideal", to be polite, and i would recommend you just bite the coding bullet and pass extra key names, or automate that by using a method to add properties to a blank object instead of coding it all in an object literal.
Yes.
Sort Of.
It depends on the browser. (Chrome=OK, Firefox=Nope)
You can use a factory to create the function, and a call stack parsing hack that will probably get me arrested.
This solution works in my version of Chrome on Windows 7, but the approach could be adapted to other browsers (if they support stack and show the property name in the call stack like Chrome does). I would not recommend doing this in production code as it is a pretty brittle hack; instead improve the architecture of your program so that you do not need to rely on knowing the name of the calling property. You didn't post details about your problem domain so this is just a fun little thought experiment; to wit:
JSFiddle demo: http://jsfiddle.net/tv9m36fr/
Runnable snippet: (scroll down and click Run code snippet)
function getCallerName(ex) {
// parse the call stack to find name of caller; assumes called from object property
// todo: replace with regex (left as exercise for the reader)
// this works in chrome on win7. other browsers may format differently(?) but not tested.
// easy enough to extend this concept to be browser-specific if rules are known.
// this is only for educational purposes; I would not do this in production code.
var stack = ex.stack.toString();
var idx = stack.indexOf('\n');
var lines = ex.stack.substring(idx + 1);
var objectSentinel = 'Object.';
idx = lines.indexOf(objectSentinel);
var line = lines.substring(idx + objectSentinel.length);
idx = line.indexOf(' ');
var callerName = line.substring(0, idx);
return callerName;
}
var Factory = {
getFunction: function () {
return function () {
var callName = "";
try {
throw up; // you don't *have* to throw to get stack trace, but it's more fun!
} catch (ex) {
callName = getCallerName(ex);
}
alert(callName);
};
}
}
var obj1 = {
'callName2': Factory.getFunction(),
'callName3': Factory.getFunction()
};
var obj2 = {
'callName4': Factory.getFunction(),
'callName5': Factory.getFunction()
};
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'

javascript - help me understand this structure (lexical scoping)

Below is simplification of some code I am trying to understand.
What are we trying to do in this javascript fragment? It seems we are creating object(?) called myCompany if not already created, then adding child object myProject to myCompany.
Then creating a local variable withinmyCompany.myProject and another local to function myCompany.myProject.myfunction. The () at the end make it execute immediately. And we are doing this to keep localVariable_1 out of global space?
var myCompany= myCompany || {};
if (!myCompany.myProject) {
myCompany.myProject = {};
}
myCompany.myProject = function () {
var localVariable_1;
function myFunction(){
var anotherlocalVariable;
// .. do some stuff
}
}();
The first line checks if the object exists, if not use shorthand definition {} to create an Object. || compares. If argument one is null set argument two.
The if on the next line checks if the property myProject isn't set on the object. ! is the operator. If myCompany.myProject returns undefined this if clause returns true. When true create object as property myProject.
Third part: myProject gets replaced by a function object. This function is defined between { and }, but is immediately called upon by the () behind the function declaration.
localvariable_1 will never be in the global scope since it has the var statement. Binding it to the scope of myCompany.myProject function. Maybe this function is directly called to set up some initial values, but wrap them in a function that could be reused to change the values at another moment.
One piece at a time...
var myCompany= myCompany || {};
if myCompany exists you set it to it, otherwise you create an empty object and set myCompany to an empty object.
NOTE: if myCompany already exists you have no indicator of what it is
if (!myCompany.myProject) {
myCompany.myProject = {};
}
Now that you know myCompany is an object you verify it has a project property on it. if not you set myProject to an empty object.
NOTE: you have tested nothing about myProject so again there is no indicator of what it is
myCompany.myProject = function () {
var localVariable_1;
function myFunction(){
var anotherlocalVariable;
// .. do some stuff
}
}();
Here you are assigning myCompany.myProject. Notice at the bottom the () before the ; That makes this function get executed immediately. Inside of the function you are creating another function that currently isn't doing anything. Where you aren't returning from the function I think it will set myProject to undefined.
You may already know what an immediate function is but if not it is basically a function that is called right away. It is also standard to wrap it in a () so that it is easier to read for example
var someFunction = (function () {
/*whatever*/
} ());
You said this was simplified from the original so I am guessing you removed an important part of the code that actually does things but the confusion is probably due to the JavaScript's way of scoping. It uses what is called Lexical scoping. You can think of it as scoping by functions.
Another thing that may be tripping you up is how JavaScript uses truthy evaluation for logical comparisons.
The last thing to mention that might be confusing the way you read the code is javascript's hoisting.
Hopefully that helps or at least points you to a few things you can look into to figure out the parts you don't exactly understand.
Sorry I just hate writing in comments lol.
If you are trying to help prevent your global scope from getting polluted then you might want to use objects and a something similar to what you are doing. Depending on how crazy you want to get you could look into Prototypical Inheritance.
A common pattern is to do something like this
var company = (function() {
var name;
var getName = function() {
return name;
};
var setName = function(n) {
name = n;
};
return {
getName : getName,
setName : setName
}
}())
Now you can do company.setName("yoda") or whatever.
This will give you a basic getter and setter where no one can change the companies name without going through your getter and setter and it also doesn't pollute the global scope. You can have whatever you want on company this way and you also encapsulate the data within the object.
Notice how var company = a function that is called immediately which returns an object that has whatever you want to encapsulate on it.
Is that what you are talking about?

Hardcore javascript module scope

The problem : I want to iterate over my list of functions, and modify them in place, using code like:
for(var funcProperty in scope) {
scope['_'+funcProperty] = scope[funcProperty];
scope[funcProperty] = wrapFunctionInTryCatchBlock(scope['_'+funcProperty]);
}
I want to do this without explicitly having to go through all my functions, and add them to some object, thereby creating the required scope. I don't want to do that because then all the functions, which call each other, will have to have their names modified and lengthened to become:
funcName becomes scopeObject.funcName : annoying.
I could do this quite easily if my functions were in the global object, i.e, Window, however I don't want to pollute the global namespace, so I have put them in a module, like so:
var MyModule = (function() {
function privateFunc1(...) {...}
function privateFunc2(...) {...}
var public_api = {
coolName : privateFunc1
};
return public_api;
}());
However, I can see and find no way to access the scope object that exists in the immediately executed function call the return value of which is assigned to MyModule.
I tried doing this, from within MyModule:
console.log(this)
To see if we did have access to the scope, somehow, yet, of course, it turned out that this referred to Window.
My question is really: What is the scope object that the methods in MyModule private scope are assigned to, since it is not the global object, and it does exist, since all the functions have implicit access to it. Is there any way I as a JavaScript programmer can explicitly access the scope object and enumerate its properties or is that FORBIDDEN?
I'm not going to rush to accept this as the answer, but I have found one possible solution that I am happy with.
Definition of "happy with" in this case is : minimal extra work, almost no changes to existing code.
The solution
We modify the module code like so:
// $ = wrapFunctionInTryCatchBlock
function $(fun) {
return function() {
try {
return fun.apply(this,arguments);
} catch(err) {
console.log("Error",err,err.stack);
}
};
}
var MyModule = (function() {
var privateFun1 = $(privateFun1(...){...});
var privateFun2 = $(privateFun2(...){...});
var public_api = {
coolName : privateFun1
};
return public_api;
}());
Why this works
We get the desired code modification (function wrapping), essentially in place since the variables assigned to function expressions have exactly the same scope as the original named functions themselves.
A VIM regex to help
I also created a VIM regex to help with this, at least the assignment line anyway:
s/function \(\w\+\)\(.\+\)$/var \1 = $(function \1\2/g

Is "this" necessary in javascript apart from variable definition

My question is dead simple.
I just casually discovered that once you have defined a property with this. into an object, you don't need to prepend this. anymore when you want to call them.
So this. is really meant to be used ad definition time, like var?
I found it my self shortly after, i was referencing the window object with this. since i called my object without using new, so like it was a function.
One extra question, maybe for comments. Inside the main object, if i create a new object, and use this during the object definition, this this what will be referring to?
No, unless the context of this is a global object, such as window. Take the following example:
function Foo(bar) {
this.data = bar;
console.log(this.data); // OK
console.log(data); // ReferenceError
}
In this example, you'll get a ReferenceError: data is not defined on the first console.log(data), unless, data is a global variable. To access the instance's public member, you have to use this.data.
References:
Understanding JavaScript’s this keyword
The this keyword
There are all sorts of circumstances where you MUST use this in order to reference the right data.
These two implementations do very different things:
Array.prototype.truncate(newLen) {
// sets the length property on the current Array object
this.length = newLen;
}
Array.prototype.truncate(newLen) {
// sets a global variable named length
length = newLen;
}
var arr = [1,2,3,4,5,6,7];
arr.truncate(2);
You MUST use this in order to control what happens if you want to modify the current object. Your assumption that you can leave it off and it will still modify the current object's properties is not correct. If you leave it off, you are modifying global variables, not member properties.
So this. is really meant to be used ad definition time, like var?
No, the point of this is to be the current scope of execution. You can (and will) run into weird errors if you don't use this. For example, imagine you are an object with a property val and then on the prototype of that object you have
App.obj = function(){
this.val = 'initial';
}
obj.prototype.myMethod = function(val) {
// how would you assign argument val to object val?
}
also note that your reasoning breaks down with methods.
obj.prototype.meth2 = function(){
myMethod(); // fails where this.myMethod() would work.
}
See http://jsfiddle.net/BRsqH/:
function f(){
this.public='hello!';
var hidden='TOP SECRET!';
}
var instance=new f();
alert('Public data: '+instance.public+ /* gives "hello!" */
'\nHidden data: '+instance.hidden /* gives undefined */
);
Variables created with var are hidden and cannot be viewed nor modified outside the function which created them.
But variables created with this are public, so you can access them outside the function.
I think I got it.
I defined my object as function My_Object(){...} and then called it with MyObject(). This way the My_Object was treated as a function, not an object and therefore this == window.
So in the end I was attaching properties and methods to window instead of My_Object! That's way there were available without prepending .this.
The right way to initialize My_Object as an object is to call it like this new My_Object, isn't right?

Categories

Resources