This question already has answers here:
What does "this" refer to in arrow functions in ES6?
(10 answers)
Closed 7 years ago.
This code below should work as expected, and log "meow", here an example.
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = () => {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
It doesn't work, this error appears TypeError: Cannot read property 'animalNoise' of undefined and when you convert the arrow function to an actual function declaration it works. It seems like with the arrow function, I no longer have access to this. What's going on here?
To be clear, the above code does not work where the following does, and I'm very curious why.
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = function() {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
Arrow functions perform lexical binding and uses the surrounding scope as the scope of this. For example, imagine (for some weird reason) you define Cat inside of a Dog constructor.
function Dog() {
// do dog like things
function Cat() { ... }
Cat.prototype.sound = () => {
// this == instance of Dog!
};
}
So whatever the surrounding scope is becomes the scope of an arrow function.
Related
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
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
I very confusing about the value of this at the moment of an invocation function using arrow functions. Let's take my example:
var obj = {
property: 5,
func1: function () {
console.log(this.property);
},
func2: () => {
console.log(this.property);
}
}
When i put this code on the browser console, an interesting thing happens, func1() will output 5 as expected *, but when i run func2 i got undefined. What is going on here? Why the value of this inside func2 makes reference to the global object(Window in this case).
I think i expect that output, because it is how it works, thats the reason why Alan and slevetman explains here and here respectively. But according to the Jason's explanation
Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?
So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?
The obj here is not the "enclosing" scope. The scope that you are defining the obj in is the "enclosing" scope.
Consider this example:
var obj = {
property: 5,
func1: function () {
let func2 = () => {
console.log(this.property);
}
func2();
},
}
obj.func1(); // logs 5
obj.func1.call({
property: 6
}) // logs 6
When the inner func2 is called, the this keyword refers to the obj as this in the wrapper func1 function refers to the obj and the func2 inherits the this value. The inner arrow function does not bind it's own this value.
The this in func2 is inheriting the value of the scope of the function itself, no more. To make it work, you'll have to make something like that :
var obj = {
property: 5,
func1: function () {
console.log(this.property); // shows 5
},
func2: () => {
console.log(this.property); // shows undefined
this.property = 6;
console.log(this.property); // shows 6
}
}
This question already has answers here:
What does arrow function '() => {}' mean in Javascript? [duplicate]
(2 answers)
Closed 7 years ago.
The following code:
angular.module('socially').controller('PartiesListCtrl', function ($scope)
{
$scope.helpers({
parties: () => {
return Parties.find({});
}
});
});
demo at Angular Meteor Tutorial
Can't understand the syntax used for parties: object. Why is => used ? Is there more explanation for this kind of anonymous function.
This is an arrow function, new syntax from ES2015 standard which was accepted this year. Not only arrow functions are shorter in declaration and sometimes looks nicer, they also share binding context with their surrounding code
!function() {
this.name = 'global';
var nonArrowFunc = function() {
console.log(this.name); // undefined, because this is bind to nonArrowFunc
}
var arrowFunc = () => {
console.log(this.name); // this taken from outer scope
}
}();
You can read more about arrow functions here and here and here
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(){);
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);