### JS this *Benson* --- ### what is this? NOTE: * this 是 JavaScript 的一個關鍵字。 * this 是 function 執行時,自動生成的一個內部物件。 * 隨著 function 執行場合的不同,this 所指向的值,也會有所不同。 * 在大多數的情況下, this 代表的就是呼叫 function 的物件 (Owner Object of the function)。 --- a simple example: ```javascript= 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? ```javascript= 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 ```javascript= func(p1, p2) obj.child.method(p1, p2) func.call(context, p1, p2) //put apply a side ``` NOTE:大家都知道前兩種,但第三種才是正常函數調用形式 --- #### The first two is just the syntactic sugar ```javascript= 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 --- ```javascript= var obj = { foo: function(){ console.log(this) } } var bar = obj.foo //bar() convert to bar.call(undefined); //obj.foo() convert to obj.foo.call(obj); ``` --- quiz ```javascript= 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() ``` --- ```javascript= const obj2 = obj.inner const hello = obj.inner.hello obj.inner.hello() //obj.inner.hello.call(obj.inner) obj2.hello() //obj2.hello.call(obj2) hello() //hello.call(undefined) ``` --- ```javascript= function hello() { console.log(this) } var a = { value: 1, hello } var b = { value: 2, hello } hello() a.hello() ``` --- ```javascript= hello() // hello.call(undefined) a.hello() // a.hello.call(a) ``` --- ```javascript= var x = 10 var obj = { x: 20, fn: function() { var test = function() { console.log(this.x) } test() }, // 如果這樣寫 就會抓到 20 ㄌ testFn: function(){ return(this.x) } } obj.fn() obj.testFn() // 他會等同於 // obj.testFn.call(undefined) // 還是 // obj.testFn.call(this) ``` --- a very good introduction. https://blog.techbridge.cc/2019/02/23/javascript-this/
{"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}]"}
    146 views