This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
This is what I think is best for making an object in js
function obj(){
var x = "hi";
this.getX(){return x;}
}
var y = new obj()
console.log(y.x); //this returns undefined
But from what I have seen, using this.variable is used more often in object creation.
I am thinking in java where things should be "private" in a class (note I have read about closures), does that apply in js?
What is considered the best way of object creation?
It sounds like you're trying to apply Java concepts to JavaScript, but things works completely differently in JS. You should check out the MDN article on JavaScript closures.
var variables exist in the closure. They are accessible from any function declared in the same scope.
var me = 'hello';
function someFunction() {
console.log(me);
}
someFunction(); //prints 'hello' to console
this variables will be directly accessible, even outside the scope, in the resulting object.
function someFunction() {
this.me = 'hello';
}
var instance = new someFunction();
console.log(instance.me); //prints 'hello' to console
Related
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I wanted to create variable name based on value sent to function in javascript.
like following, when i call function variable : variable("zebra"); this should return variable name as zebra1
function create variable(i){
return i+"1";
}
var variable("zebra")="abc";//this line should create variable zebra1 and initialise as abc
Try:
window['zebra'] = 'abc';
The window object holds all the global variables, assuming this is a request for global variables.
To specifically answer your question, you could put return window[i + '1'] = 'abc'; in your variable naming function.
Alternatively, you could create a global (or local) object named variables to hold all your variables:
function whoknows() {
var variables = {};
variables['zebra'] = 'abc';
}
Read more on working with objects at mozilla.org
You can create global variable with
window["zebra"] = "abc";
and use later ether with the same indexer syntax or directly - zebra.
This question already has answers here:
What is the use of the JavaScript 'bind' method?
(23 answers)
Closed 7 years ago.
Met the code first time:
var Controller = function($scope){
this._scope = $scope;
}
Controller.$inject = ['$scope'];
Controller.prototype.augmentScope = function() {
this._scope.a = {
methodA: this.methodA.bind(this)
}
}
I really don't understand what is the point. Any explanations?
It assumes that in the closure scope (If none it will be in the global scope such as window) there is a method called methodA. Then again, because the this is really the enclosing scope mentioned), it will remind it and assign it ti be used be through object a as well.
So you can execute it by:methodA() or a.methodA()
Edit to explain closure:
Although Javascript is very similar to Java/C++ in syntax it's quite different than both of them in the sense that when a function is instantiated as an object, it remembers the scope it was instantiated in. I would highly recommend anyone doing more than the casual JS(if there is such a thing), to look into this article.
The this in JS will deffer depends if it was created inside an instantiated function - AKA: new MyClass(). Referring to a literal object such as:
var myObj={a:this.b}
will not create a new this and will by default refer to enclosing scope. If none was created it will be the global object such as window in a browser
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.
This question already has answers here:
In Javascript, why is the "this" operator inconsistent?
(8 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 9 years ago.
hi i am a little confusion on how exactly this works in javascript.Based on this example:
var myFunction = function(){
function testMe(){
console.log(this) --------> DOMwindow
}
console.log(this) ---------> myFunction
}
var myvariable = new myFunction();
What is happening here?
The value this references depends on circumstances. Any unscoped (i.e. not in an object) function call will have this = window (DOMWindow, if you prefer). Anything that is part of a prototype, or has been changed using apply or bind, will have this as that object ("itself", if you prefer).
So, to illustrate. When you are instantiating using the new keyword, your function automatically inherits this as itself. When you call an IETF within it, this within this IETF will point to the global scope.
If you would like to avoid this, instead of calling testMe literally, you can always do this:
var myFunction = function() {
var testMe = function() {
console.log(this);
}
testMe.bind(this);
}
Which will, in turn, have this within testMe use the object as it should.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
seems stupid question but just curious.
num = "hello";
alert(num);
why is this possible I didnt initialize the num variable here.
num = "hello";
instead of
var num = "hello";
var means "Scope this variable to this function" not "Make it possible to use this variable".
If you leave var off then it will use the variable in the next scope up from the function. If that scope doesn't have the var yourVar then it will keep going up the scope chain until it becomes a global and dangles off the window object (assuming a browser or another JS environment in which the default object is window).
(This changes in strict mode, which you are presumably not using.)
Without the var keyword the variable is created at the global scope (in browsers under window).
If you add the var you just assign the variable to the current scope, which in most cases will be a function scope.
In general it will be better to use a function scope in order to not pollute the global scope and prevent conflicts between multiple variables of the same name!