That interesting things about javascript this scope, let's review code together
function foo(){
console.log(this)
}
foo()
This code will output window
object in browser env.
Try review other code once more
let bar = {
myName : "myName1",
test1 : 1
}
function foo(){
this.myName = "myName"
}
foo.call(bar)
console.log(bar)
console.log(myName)
Will output
// {myName: "myName", test1: 1}
// VM289:11 Uncaught ReferenceError: myName is not defined
at <anonymous>:11:13
(anonymous) @ VM289:11
What happen why i got exception? it hard to understand?
Don't worry just follow my step.
First if call function without with object like this method()
javascript will call method on global context, here global in window
object
At code foo.call(bar)
will bind bar
object to foo and this will point to bar also you have another methods to do this like apply
,bind
.
difference call
method bind
just bind method context to foo
and this will point to bar
difference call
method apply
just argument like foo.apply(bar,[arg1,arg2])
Ok let's back, console.log(bar)
will output {myName: "myName", test1: 1}
because execute foo.call(bar)
then this.myName='myName'
bar
object myName
will be overwrite.
Emmmm... how about exceptions happen? call console.log(myName)
in global context, javascript will found myName
attrs in global scope. but you know global env haven't defined myName
variable. this is main reason why exception.
So far i have show you two javascript code about how context effective behavior, one words function context this
will follow call object. if no object indicate. global object will replaced
Short words
foo() // `this` will point to global object like: window, global
obj.foo() // `this` will point to obj
Top comments (0)