JS this

Benson


what is this?

NOTE:

  • this 是 JavaScript 的一個關鍵字。

  • this 是 function 執行時,自動生成的一個內部物件。

  • 隨著 function 執行場合的不同,this 所指向的值,也會有所不同。

  • 在大多數的情況下, this 代表的就是呼叫 function 的物件 (Owner Object of the function)。


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) //put apply a side

NOTE:大家都知道前兩種,但第三種才是正常函數調用形式


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() convert to bar.call(undefined); //obj.foo() convert to 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() //obj.inner.hello.call(obj.inner) obj2.hello() //obj2.hello.call(obj2) hello() //hello.call(undefined)

function hello() { console.log(this) } var a = { value: 1, hello } var b = { value: 2, hello } hello() a.hello()

hello() // hello.call(undefined) a.hello() // a.hello.call(a)

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/

Select a repo