this对象是在运行时基于函数执行环境绑定的,在全局函数中,this=window,在函数被作为某个对象的方法调用时,this等于这个对象. 但是匿名函数的执行环境是全局性的,所以匿名函数的this指向是window var name = 'window' var person = { name :'Alan', sayName:function () { return function () { console.log(this.name) } } } person.sayName()() /
重新看了下闭包,在javascript高级程序设计第二版里的闭包里有如下例子,例子中介绍说匿名函数的执行环境具有全局性和this指向window,对于这句话很费解,所以就想个方法验证下. var name = "The Window"; var object = { name : "My Object", getNameFunc : function(){ return function(){ return this.name; }; } }; alert(obje
今天收到RSS订阅中有一篇<Javascript – Arraylike的7种实现>,看第一种实现方式是,瞬间被!function(){}()这种匿名函数自执行方式给亮瞎了眼睛.这种写法绝对是装逼神器,代码如下: !function () { //通过闭包实现 var List = function () { var list = [], self = { constructor: List, //如果希望更像原生一点,将length定义为属性,那么length则需要自己维护 length:
匿名函数中(function(){}).call(this) 中的.call(this) 有什么用? 我们都知道,.call()可以改变函数执行时的context,即this的指向,源码中的.call(this) 主要就是,把当前的context传递给匿名函数. So, if for whatever reason you use this, it's a way to make the IIFE act as if it were a member function of Foo, speci