The 'this' keyword in a function [duplicate] - javascript

This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!

Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)

The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.

Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);

Related

JavaScript field access from anonymous function [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
how can I access a fiel from within an anonymous function inside a method?
like in this example:
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
this will result in an error that "this" is undefined.
thank you very much in advance, I could not find an answer in the web after searching for hours.
best,
lev
In your anonymous function, this is bound to the function; it no longer refers to the class.
Use an arrow function instead, which doesn't have it's own this binding.
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
new Something().doSomething();
Alternatively, you could use something like .call(), .apply(), or .bind():
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function() {
console.log(this.gax);
}).call(this);
}
}
new Something().doSomething();
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function () {
console.log(this.gax);
}).apply(this);
}
}
new Something().doSomething();
You can use apply method. The apply() method calls a function with a given this value

Referring to Class instantiater in javascript [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have this method of a JavaScript class that I've created:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
newRule.sheet.deleteRule(i);
}
});
}
when you instantiate a class, it essentially has to be set to a variable, like so:
const newRule = new NewRule(*params*);
and the methods/properties of said class can refer to the class object using this. like so:
this.method();
this.property;
What I'd like to know is: how does one refer back to the variable that instantiated the class within a function that is called by a method of said class?
To be even clearer: a function that is called within a method of a class alters the scope, which also means it alters the definition of this.. My question is: how do you get around this? How could you access the variable that instantiated the class when you are out the of scope of the methods within said class?
As I was composing this question, I realized that you can set the this value for a .forEach loop like this:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
this.sheet.deleteRule(i);
}
}, this);
}
However, the way this code works is something that--as far as I know--is just a benefit of the .forEach method, and I'd still like to know how it should be handled in general.
Hopefully this should help you out, using your example.
class Rule {
constructor(rules) {
this.sheet = {
rules: rules || []
}
}
log(){
console.log('rules:',this.sheet.rules)
}
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
let self = this; // <-- here you can capture the instance
sheetRules.forEach(function(node, i) {
self.log() // <-- here you can use it in forEach
if (node.name != undefined)
this.sheet.deleteRule(i);
});
}
}
const fooRule = new Rule(['foo'])
const barRule = new Rule(['bar'])
fooRule.resetRule()
barRule.resetRule()
fooRule.log()
barRule.log()
Your forEach works because as you discovered, you passed this as an argument for the thisArg parameter. However, if you didn't, you could have just as easily set it to a variable in the outer scope and used it in the block scope.
Generally creating a variable called self or that and setting it to this is helpful, especially for arrow functions, which set this to the encapsulating scope and not the instance object.
You could make a temporary variable called self or something which would allow you to use both the object containing "this" instance as well as within that anonymous function passed to forEach, this which will refer to sheetRules when you don't specify another variable to use as this
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
let self = this;
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
self.sheet.deleteRule(i);
}
});
}
If I've not misunderstood you're looking for a way to retain your scope? You have a few options here.
The immediate answers would be to use Function.prototype.bind() or Function.prototype.call() to specify the context of this when invoking those methods.
Alternatively you could just make the scope of your this available where needed:
var MyClass = function () {
// Here we bind the local scope to a variable that will give us context where necessary.
// While it's not needed here, it can give context and set a pattern of reability through repitition.
var vm = this;
vm.methodA = function () {
// We continue to set our 'vm' pointer variable when needed.
var vm = this;
globalMethod.then(function () {
// We're able to retain context of our `this` through having scope of our 'vm' variable.
vm.methodB();
});
};
vm.methodB = function () {
console.log('I did stuff!');
};
};

Best way to declare functions on javascript objects [duplicate]

This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 4 years ago.
When defining javascript objects that behave like classes that have state and functions that manipulate that state is it better to define functions when defining the object like so:
function MyNewClass(){
//State
this.value = ""
this.otherValue = ""
//Functions
this.someFunction = function(){
//Some logic here
}
}
Or it it better practice to define functions on the prototype of the object such as:
function MyNewClass (){
//state
this.value = ""
this.otherValue = ""
}
MyNewClass.prototype.someFunction = function(){
//Some logic here
}
Are there any advantages to defining object functions on the prototype?
Thanks!
Because functions are objects, given the described scenario, we have two behavior:
If you declare the function on the "class" function, every object you
create then it will have a copy of that function (object), so the
memory usage will increase.
However, if you add the function to the prototype, the function will
be shared by all the objects, so there will be a save of memory
You can see the difference for yourself by running this code:
var output = function(s) { document.getElementById("output").innerText += s; }
function MyNewClass() {
this.foo = function() {
output("1");
}
}
MyNewClass.prototype.bar = function(){
output("2");
};
var a = new MyNewClass();
a.foo();
a.bar();
a.foo = function() { output("3") };
MyNewClass.prototype.bar = function() { output("4"); };
a.foo();
a.bar();
var b = new MyNewClass();
b.foo();
b.bar();
The output is: 123414
When you change a function as a member variable, you only change that instance. If you change it in the prototype, it affects all instances.
functions of the object should be declared using prototype because prototype is a common space that is shared by all the objects created by the same constructor function and it also saves memory because all objects do not have there own functions created but they all are pointing to one common place.
you can refer it here
https://www.youtube.com/watch?v=fBpPfPjxOhc&list=PLqq-6Pq4lTTaflXUL0v3TSm86nodn0c_u
example
enter code here
//constructor function
function gh(){
this.x=1;
}
//now if you create a object
var p=new gh();
//now i need function show in my object p
function show(){
console.log(x);
}
gh.prototype.show=show();
//it will be added all objects automatically (to understand this study scope chain)

Use of writing function in specified manner in javascript or angularjs [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
I have been writing functions like
var functionname = function(param)
{
}
rather then
functionname(param)
{
}
does it provide any advantage of the format or any garbage collection happens when i write like the first syntax?
(function() { "use strict"; f(); function f() { console.log(1); }; })();
1
(function() { "use strict"; f(); var f = function() { console.log(1); }; })();
Object expected
Function expressions var name = function() { ... } are not hoisted, while function decarations function name() {...} are.
first of all, u should understand the scope matter for this function.
when u write:
var a = function(){} --> the function is anonymous outside the var a- scope.
it means, that out of this district, the function will not be able to be accessed. another thing is memory usage- here u create a function which takes memory, and a pointer outside the function pointing on it as a soft link.
when u write function a(){} ---> there is a public pointer named a for this function as a hard link.
so, if you want to create a private function- go for it.
i know that it's common to create functions using: function funcName(){);

Syntax of variable declaration? var a = (function() { })() [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
var f1 = function() {
console.log('bar');
};
And you could subsequently call it like so:
f1();
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions: incrementCounter and resetCounter. You can call them like so: testModule.incrementCounter() and testModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
The anonymous function is executed and the return value is assigned to the variable.

Categories

Resources