好比说有这么一段代码:javascript
var O = function(data){ this.data = data } O.prototype.selfCall = function(data){ if(data.length>1){ data.forEach(function(e){console.log(this)}) }else{ console.log(this); } } var o = new O("test") o.selfCall([1]) o.selfCall([1,2])
输出的结果是:java
O { data: 'test' } { DTRACE_NET_SERVER_CONNECTION: [Function], DTRACE_NET_STREAM_END: [Function], DTRACE_HTTP_SERVER_REQUEST: [Function], DTRACE_HTTP_SERVER_RESPONSE: [Function], DTRACE_HTTP_CLIENT_REQUEST: [Function], DTRACE_HTTP_CLIENT_RESPONSE: [Function], ...
第一个输出的this是确实指向了对象O,可是第二个由于套了一个function,因此这时候的this就指向了函数自己。
若是想用this指向O的话,能够这么写:segmentfault
O.prototype.selfCall = function(data){ n = this if(data.length>1){ data.forEach(function(e){console.log(n)}) }else{ console.log(this); } }
就是在函数外面用n存一下this,以后靠着函数的lexical(是这么说的么?)关系,拿外层的n来引用O。不过前段时间看过别人讲=>能够传递this。当时不知道这有什么意义,如今看来确实是很好的一个特性。因此上面的程序能够改为这样:函数
O.prototype.selfCall = function(data){ if(data.length>1){ data.forEach(e=>{console.log(this)}) }else{ console.log(this); } }
总结:this
function(){}里面的this指代的是function自己prototype
能够经过lexical scope借助一个变量把外面的this传进function(){}code
=>不单单让匿名函数的书写更简单,还有一个很是好的特性:this的传递对象
=>同时还会避免arguments指向匿名函数:参见回调+遍历ip