what is this?
a simple example:
| var getGender = function(){ |
| return this.gender; |
| }; |
| |
| var people1 = { |
| gender: 'female', |
| getGender: getGender |
| }; |
| |
| var people2 = { |
| gender: 'male', |
| getGender: getGender |
| }; |
| |
| console.log( people1.getGender() ); |
| console.log( people2.getGender() ); |
what is the following ans?
| var obj = { |
| foo: function(){ |
| console.log(this) |
| } |
| } |
| |
| var bar = obj.foo |
| obj.foo() |
| bar() |
Let's learn it step by step!
there's three way to call func
| func(p1, p2) |
| |
| obj.child.method(p1, p2) |
| |
| func.call(context, p1, p2) |
| |
| |
The first two is just the syntactic sugar
| func(p1, p2) |
| |
| func.call(undefined, p1, p2) |
| |
| obj.child.method(p1, p2) |
| |
| obj.child.method.call(obj.child, p1, p2) |
Context
- strict mode -> undefined obj
- in browser -> window
| var obj = { |
| foo: function(){ |
| console.log(this) |
| } |
| } |
| |
| var bar = obj.foo |
| |
| |
| bar.call(undefined); |
| |
| |
| obj.foo.call(obj); |
| |
quiz
| const obj = { |
| value: 1, |
| hello: function() { |
| console.log(this.value) |
| }, |
| inner: { |
| value: 2, |
| hello: function() { |
| console.log(this.value) |
| } |
| } |
| } |
| |
| const obj2 = obj.inner |
| const hello = obj.inner.hello |
| obj.inner.hello() |
| obj2.hello() |
| hello() |
| const obj2 = obj.inner |
| const hello = obj.inner.hello |
| |
| obj.inner.hello() |
| |
| |
| obj2.hello() |
| |
| |
| hello() |
| |
| function hello() { |
| console.log(this) |
| } |
| |
| var a = { value: 1, hello } |
| |
| var b = { value: 2, hello } |
| |
| hello() |
| |
| a.hello() |
| var x = 10 |
| var obj = { |
| x: 20, |
| fn: function() { |
| var test = function() { |
| console.log(this.x) |
| } |
| test() |
| }, |
| |
| testFn: function(){ |
| return(this.x) |
| } |
| } |
| |
| obj.fn() |
| |
| obj.testFn() |
| |
| |
| |
| |
JS this Benson
{"metaMigratedAt":"2023-06-15T16:17:22.207Z","metaMigratedFrom":"YAML","title":"JavaScript this","breaks":true,"slideOptions":"{\"theme\":\"solarized\",\"transition\":\"slide\"}","contributors":"[{\"id\":\"156b7bd7-bc36-4924-b2f2-88f18442b450\",\"add\":2407,\"del\":45},{\"id\":\"82eaa412-2ff3-4bfe-bbd7-5ff190dd3326\",\"add\":426,\"del\":220}]"}