"this" not working inside the function kindly guide

"this" not working inside the function kindly guide



I was thinking i had pretty good understanding of “this” , but apparently not , i was stumped when this code would return undefined –

function testName(fName) {
       return this.fName ;

How come this is not working here , should it not refer to the value fName as it acts according to the context it is called, kindly guide please …



this refers to the context, yes, but it’s the context of an object. So you access objects like:

var foo = {
  fName: 'bar'
> foo.fName

this refers to whatever is literally to the left of the dot from whatever you’re calling. So like:

foo = {
  fName: 'bar',
  testName() {
    return this.fName:
> foo.testName()

So testName is called in the context of foo. So this is foo, and foo.fName is 'bar'.

In your example, the context is window in the browser, the global context. So when you say return this.fName, this is window, window.fName doesn’t exist, so you’ll get either an error or undefined. Kinda like:

window = {
  testName(fName) {
> window.testName('bar')
undefined # window.fName is not defined anywhere


@DanCouper - thanks , i was under impression that even inside the function it works like in object, here it seem to take the window as context …


Yeah, the parameter fName is scoped to the function. Access only goes one way: the function can access values scoped in parent contexts, but parents cannot access values scoped within child function contexts


Nope, that doesn’t work, that’s not how constructor functions work, and it doesn’t do what you say it does. Firstly, you meant return this.name. but you don’t return in a constructor function. When you console.log(x), it just logs an object: the new testName(88) creates an object that looks like { name: 88 }, it doesn’t return anything. It’ll create the object, in this case, under the name x, so you can then log x.name which will log 88