博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一语道尽 this
阅读量:7035 次
发布时间:2019-06-28

本文共 1752 字,大约阅读时间需要 5 分钟。

this 的指向,apply、bind、call 一起搞定~

this

this 是在执行函数时,创建的上下文对象中的一个属性,它允许在调用函数时决定哪个对象是焦点。所以 this 一般是在函数执行时确定的

this 指向的是谁

一般情况下,请记住 "谁调用我,我就代表谁"。

谁调用这个函数,函数中的 this 就指向谁。

var name = 'window'function foo() {    var name = 'foo'    console.log(this.name)}foo() // 'window'复制代码

执行 foo() 相当于执行 window.foo()(非严格模式) 也就是 window 调用了 foo 函数,所以 foo 函数体内的 this 指向的就是 window 对象。

当然如果是在 Node.js 环境下,上述 this 指向的就是 globle 对象了。

匿名函数中的 this 也是指向全局对象的。

再看个例子:

var name = 'window'var a = {    name: 'a',    foo: function() {        console.log(this.name)    }}a.foo()  // 'a'var foo2 = a.foofoo2()  // 'window'复制代码

改变 this 的指向

new 实例化对象。

new 运算符做了:申请内存用于储存对象,将 this 指向该对象,执行构造函数代码,返回对象给变量。

function User(name) {    this.name = name}var a = new User('小a')复制代码

_this = this

var name = 'window'var a = {    name: 'a',    foo: function() {        setTimeout(function() {            console.log(this.name)        }, 0)    },    foo2: function() {        var _this = this        setTimeout(function(){            console.log(_this.name)        }, 0)    }}a.foo()  // 'window'a.foo2()  // 'a'复制代码

apply、call、bind

apply 与 call 差不多,主要是传参不同,都是将 this 改变并执行函数,而 bind 是将函数返回但没执行。

var name = 'window'var a = {    name: 'a',    foo: function(x, y) {        console.log(this.name + x + y)    }}a.foo.call(this, 1, 2)  // 'window12'a.foo.apply(this, [1, 2])  // 'window12'var foo2 = a.foo.bind(this, 1, 2)foo2()  // 'window12'复制代码

箭头函数

箭头函数不绑定 this,没有自己的 this ,必须通过作用域链决定其值。也就是箭头函数中的 this 就是父级作用域中的 this

var name = 'window'var a = {    name: 'a',    foo: () => {        console.log(this.name)    },    foo2: function() {        setTimeout(()=>{            console.log(this.name)        }, 0)    }}a.foo()  // 'window'a.foo2()  // 'a'复制代码

参考资料:

转载于:https://juejin.im/post/5ca55d8a51882543b958ccff

你可能感兴趣的文章
kudu 1.8.0(开发版) 源码安装
查看>>
LVS+Keepalived实现MySQL从库读操作负载均衡
查看>>
【转载】说说标准服务器架构(WWW+Image/CSS/JS+File+DB)续测试环境搭建
查看>>
day13-类的重写和类的私有方法
查看>>
[LeetCode][Java] Unique Paths II
查看>>
哈理工2015 暑假训练赛 zoj 2976 Light Bulbs
查看>>
Notes for C++
查看>>
web前端职业规划(转)
查看>>
用户体验 的一个原则,
查看>>
常用面试sql语句
查看>>
Kafka - 消费接口分析
查看>>
<s:property value=""/> 获取属性时的各种方式
查看>>
RF-RequestsLibrary
查看>>
【HDOJ】1892 See you~
查看>>
同伦延拓法中的几个数学常识
查看>>
毕业论文如何排版
查看>>
JS3 -- 模块(cmd amd)
查看>>
转:机器学习算法笔记:谱聚类方法
查看>>
浮点数转换成二进制
查看>>
关于python中的enumerate函数的应用
查看>>