0

I am having tough time understanding the scope of thisin Javascript.

I am following some tutorial on web but my instructor did something which he advised not to do when explaining b

for example at the start of the instruction he said

var person = "roht" 

function whatIsThis() {
    return this
    console.log(this)
}

function variable (){
    this.person = "max"
}
variable()
console.log(person)

whatIsThis()

When I run this.person it will attach value to the global object which is a bad practise (since this have global scope)

but later he himself this thing endless number of time when explaining creating a new object using fucntion constructor

function Person(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName 
}
var elie = new Person("james", "roger");

I am sure that I am missing something, can someone help me figure this out?

  • The difference is between just calling a function normally vs using `new`. Side note - having a `console.log` (or any other code) after a `return` makes no sense. A return ends the function. – takendarkk Mar 27 '18 at 19:30
  • 1
    Considering `function f(){this;}`, when you write `f()`, `this` is set to `window` by default, and when you write `new f()`, a new object is created and `this` is set to the new object. Also, you can set `this` to a custom value with `.call()`, `.apply()` or `.bind()`, like so : `f.call(customValue)`. –  Mar 27 '18 at 19:57

0 Answers0