1、函数中this 总是指向调用的对象
2、箭头函数中的this 指向上下文
this 说来说去 不过上面两点。看下下面几个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()
函数在浏览器全局环境中被简单调用; this 指向window,严格模式为undefined
2、demo2
const person = {
name: 'GGGG',
brother: {
name: 'HHHH',
fn: function() {
return this.name
}
}
}
console.log(person.brother.fn())
输出HHHH; this 指向调用对象, 调用对象为 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个o1 实际内部o1.fn 的调用对象为o1, 所以输出o1; 第3个中内部的fn 的调用对象实际为 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())
改变函数中this 指向的两种方法,一种方式为 call/apply/bind ; 另一种方式为 直接赋值
4、demo4
const foo = {
fn: function () {
setTimeout(() => {
console.log(this)
})
}
}
console.log(foo.fn())
// {fn: ƒ}
箭头函数中的this 满足第2条
5、demo5
function Foo() {
this.bar = "hhhhh"
}
const instance = new Foo()
console.log(instance.bar)
构造函数中的this行为:
- 创建一个新的对象;
- 将构造函数的 this 指向这个新对象;
- 为这个对象添加属性、方法等;
- 最终返回新对象。
以上过程同:
var obj = {}
obj.__proto__ = Foo.prototype
Foo.call(obj)
构造函数有显示返回值时:
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 指向实例。
具体见:一道前端小题的简单分析 最后一部分的解释~~
hi~~~ 有帮助么, 点个赞吧~~
网友评论