1、函數(shù)中this 總是指向調(diào)用的對(duì)象
2、箭頭函數(shù)中的this 指向上下文
this 說來說去 不過上面兩點(diǎn)??聪孪旅鎺讉€(gè)demo加深下理解
1、demo1
function f1 () {
console.log(this)
}
function f2 () {
'use strict'
console.log(this)
}
f1() // window
f2() // undefined
const foo = {
bar: 10,
fn: function() {
console.log(this)
console.log(this.bar)
}
}
var fn1 = foo.fn
fn1()
函數(shù)在瀏覽器全局環(huán)境中被簡單調(diào)用; this 指向window,嚴(yán)格模式為undefined
2、demo2
const person = {
name: 'GGGG',
brother: {
name: 'HHHH',
fn: function() {
return this.name
}
}
}
console.log(person.brother.fn())
輸出HHHH; this 指向調(diào)用對(duì)象, 調(diào)用對(duì)象為 person.brother
const o1 = {
text: 'o1',
fn: function() {
return this.text
}
}
const o2 = {
text: 'o2',
fn: function() {
return o1.fn()
}
}
const o3 = {
text: 'o3',
fn: function() {
var fn = o1.fn
return fn()
}
}
console.log(o1.fn())
console.log(o2.fn())
console.log(o3.fn())
輸出為 o1 o1 undefined; 第2個(gè)o1 實(shí)際內(nèi)部o1.fn 的調(diào)用對(duì)象為o1, 所以輸出o1; 第3個(gè)中內(nèi)部的fn 的調(diào)用對(duì)象實(shí)際為 window , 所以輸出為undefined
3、 demo3
const foo = {
name: 'hhhhh',
logName: function() {
console.log(this.name)
}
}
const bar = {
name: 'mike'
}
console.log(foo.logName.call(bar))
const o1 = {
text: 'o1',
fn: function() {
return this.text
}
}
const o2 = {
text: 'o2',
fn: o1.fn
}
console.log(o2.fn())
改變函數(shù)中this 指向的兩種方法,一種方式為 call/apply/bind ; 另一種方式為 直接賦值
4、demo4
const foo = {
fn: function () {
setTimeout(() => {
console.log(this)
})
}
}
console.log(foo.fn())
// {fn: ?}
箭頭函數(shù)中的this 滿足第2條
5、demo5
function Foo() {
this.bar = "hhhhh"
}
const instance = new Foo()
console.log(instance.bar)
構(gòu)造函數(shù)中的this行為:
- 創(chuàng)建一個(gè)新的對(duì)象;
- 將構(gòu)造函數(shù)的 this 指向這個(gè)新對(duì)象;
- 為這個(gè)對(duì)象添加屬性、方法等;
- 最終返回新對(duì)象。
以上過程同:
var obj = {}
obj.__proto__ = Foo.prototype
Foo.call(obj)
構(gòu)造函數(shù)有顯示返回值時(shí):
function Foo(){
this.user = "hhhhh"
const o = {}
return o
}
const instance = new Foo()
console.log(instance.user)
輸出undefined; this指向o
function Foo(){
this.user = "hhhhh"
return 1
}
const instance = new Foo()
console.log(instance.user)
輸出hhhhh; this 指向?qū)嵗?br> 具體見:一道前端小題的簡單分析 最后一部分的解釋~~
hi~~~ 有幫助么, 點(diǎn)個(gè)贊吧~~