标签:win 改变 blog app 方法 class define 简单 nbsp
js中的this指向(较简单的几种):
1.普通函数的this指向window;
2对象方法指向当前对象;
3.()=》箭头函数指向定义时的对象;
apply和call可以改变当前的this指向,但是不能改变箭头函数的指向
function foo() { return () => { return () => { return () => { console.log(‘id:‘, this.id); }; }; }; } var f = foo.call({id: 1}); var t1 = f.call({id: 2})()(); // id: 1 var t2 = f().call({id: 3})(); // id: 1 var t3 = f()().call({id: 4}); // id: 1
上面举了个例子,说明箭头函数的this是不能改变的,相反,如果是普通匿名函数,就可以改变:
function foo() { return () => { function() { console.log(‘id:‘, this.id); }; }; } var f1 = foo.call({id: 1})()()//undefined; var f2 = foo().call({id: 1})()//undefined; var f3 = foo()().call({id: 1})//1
前两个this最后指向了window,最后一个指向{ID:1}
标签:win 改变 blog app 方法 class define 简单 nbsp
原文地址:http://www.cnblogs.com/walei/p/7132547.html