杂记——简单理解上下文和this

来源:互联网 发布:汉奇中走丝编程视频 编辑:程序博客网 时间:2024/05/27 20:51

直接上代码

var User = {    count: 1,    getCount: function() {            return this.count;    }};console.log(User.getCount());var func = User.getCount;console.log(func());

输出 1 和 undefined

为什么呢?

因为func是在window的上下文中被执行的,所以会访问不到count属性。

那怎么样才能访问到count属性呢?

可以使用Function.prototype.bind();Function.prototype.apply();Function.prototype.call();

var func = User.getCount.bind(User);console.log(func());
var func = User.getCount.apply(User);console.log(func);
var func = User.getCount.call(User);console.log(func);
阅读全文
0 0