Benson
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() );
var obj = {
foo: function(){
console.log(this)
}
}
var bar = obj.foo
obj.foo()
bar()
func(p1, p2)
obj.child.method(p1, p2)
func.call(context, p1, p2)
//put apply a side
NOTE:大家都知道前兩種,但第三種才是正常函數調用形式
func(p1, p2)
func.call(undefined, p1, p2)
obj.child.method(p1, p2)
obj.child.method.call(obj.child, p1, p2)
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/
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing