原文:http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html
一. 来猜猜this的输出吧
//定义一个全局变量 var name = 'haha'; //定义一个全局函数 function getName1() { return this.name; } //定义一个构造方法 function Person() { this.name = 'byvoid'; this.nameno = 'fuck'; this.toString2 = getName2; this.toString3 = getName2(); function getName2() { return this.nameno; } this.test = function () { return this.name; }; this.test2 = () => { return this.name }; } var obj = new Person(); console.log('1.' + getName1()); obj.m = getName1; console.log('2.' + obj.m()); obj.n = getName1(); console.log('3.' + obj.n); console.log('4.' + obj.toString2()); console.log('5.' + obj.toString3); console.log('6.' + obj.test()); console.log('7.' + obj.test2()); obj.test3 = () => { return this.name }; console.log('8.' + obj.test3()); obj.test4 = function () { return this.name } console.log('9.' + obj.test4());
二. 结果
我打赌你肯定会猜错几个,比如第5,8,9项很有可能猜错其中2项
1.haha 2.byvoid 3.haha 4.fuck 5.undefined 6.byvoid 7.byvoid 8.haha 9.byvoid
三. 用注释解释,给出关键知识点
如果没有系统的了解过this相关,建议读者先去看看这篇博客:阮一峰:Javascript的this用法
其中有几个点没有讲到,请看代码注释.
//定义一个全局变量 var name = 'haha'; //定义一个全局函数 function getName1() { return this.name; } //定义一个构造方法 function Person() { this.name = 'byvoid'; this.nameno = 'fuck'; this.toString2 = getName2; this.toString3 = getName2(); function getName2() { return this.nameno; } this.test = function () { return this.name; }; this.test2 = () => { return this.name }; } var obj = new Person(); console.log('1.' + getName1()); //输出haha, 正常的全局函数调用, this指向全局对象 obj.m = getName1; console.log('2.' + obj.m()); // 输出byvoid,作为对象的方法调用,this指向obj obj.n = getName1(); console.log('3.' + obj.n); //输出haha,obj的n实际上是调用getName1()函数进行赋值,this指向全局对象 console.log('4.' + obj.toString2()); //输出fuck,调用obj对象的方法,this指向obj console.log('5.' + obj.toString3); //输出undefined,这个有点难以理解,实际上toString3在定义的时候就调用了getName2()进行求值,这时getName2()的执行环境是全局环境,而全局中没有定义nameno,所以输出undefined console.log('6.' + obj.test()); //输出byvoid,调用obj对象的方法,this指向obj console.log('7.' + obj.test2()); //输出byvoid, 箭头函数的this就是外层闭包的this对象(请把箭头函数当做一段普通代码) obj.test3 = () => { return this.name }; console.log('8.' + obj.test3()); //输出haha,临时在全局环境给obj定义一个成员test3,这时箭头函数的外部闭包是全局环境,因此this指向全局对象 obj.test4 = function () { return this.name } console.log('9.' + obj.test4()); //输出byvoid,这个是用来与第8中情况做对比,证明箭头函数和普通函数的区别
结语
作者:山中小僧
链接:http://www.jianshu.com/p/f5749a71e7d1
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。