js:this
来源:互联网 发布:大数据走势 找规律 编辑:程序博客网 时间:2024/06/02 02:59
这是一道面试题。
加上前些天看了几篇文章,有篇文章讲得不错,拿出来说说。
传送门:http://mp.weixin.qq.com/s/ksqtCd8ouxU-cVc_HnA4Aw
函数调用
函数调用的三种方式
func(a, b);obj.method(a, b);func.call(context, a, b);
似乎前两种我们更加频繁地使用,而第三种则不常用到。
但其实,第三种才是函数调用的真正关键所在。也就是说,可以用第三种的写法来替代前两种。
如何替代呢?
func(a, b);//等价于func.call(undefined, a, b);obj.method(a, b);//等价于obj.method.call(obj, a, b);
现在来看一段代码
var obj = { foo: function(){ console.log(this) }}var bar = obj.fooobj.foo() // 打印出的 this 是 objbar() // 打印出的 this 是 window
原因就在于
bar()//等价于bar.call(undefined);obj.foo()//等价于obj.foo.call(obj, a, b);
this丢失问题
var bar = obj.foo
你明明想的是this指向的是obj,但是他却指向了window。
这就是this丢失问题。
如何解决?
var bar = obj.foo.bind(obj);
0 0
- jquery&js $(this) & this
- js this
- JS this
- JS this
- js this
- js this
- js this
- js this
- JS this
- [js] this
- js--this
- js--this
- js this
- JS- this
- js--this
- js:this
- js this
- js this和$(this)区别
- Mongodb学习笔记
- 关于Date类型转换成毫秒数会出现误差
- unity3d中水草海草摇动效果顶点动画材质
- Linux网络命令及其其他
- 核范数与规则项参数选择
- js:this
- Sublime+node开发插件设置
- JDBC浅析
- linux进程管理笔记
- this,context,getActivity()和getApplicationContext()
- DNS字典爆破
- vue-事件修饰符和按键修饰符
- TabBarController
- spring扫描包管理bean