关于this
代码1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script type="text/javascript"> var a={ foo:function(){ } af:function(){ console.log(this); }, b:{ bb:function(){ console.log(this); } }, c:{ cc:{ cccf:function(){ console.log(this); } } } } a.b.bb();//这里this指向的时b a.b.bb.call(Window);//this指向的是Window a.b.bb.call(a);//this指向的时a </script> </head> <body> </body> </html>
这个知乎的总结的很好 都是大牛在回答呢
http://www.zhihu.com/question/19636194
首先看杨志的这句话
when a function of an object was called , the object will be passed to the execution context as 'this' value
当调用一个对象的function时 这个function中的this就是当前对象
再看灰目的这句
this由context决定,如果未指定,则指向全局变量本身
因此
foo();//这里的this是window
a.af();//这里的this是a
a.b.bb();//这里this指向是b
再看wyatt-pan说的
JavaScript 中的 this 关键字并不像 Java 或者其他语言一样是在字面意上的值, JavaScript 中的 this 关键字是在函数调用的时候被确定的
再看 张立理 说的
foo.bar()
在这种模式下,bar函数体中的this永远为“.”或“[”前的那个对象,如上例中就一定是foo对象。
function Foo(name){
this.name=name;
}
f1=new Foo('n1');
console.log(f1.name);//n1
在这种模式下,foo函数内部的this永远是new foo()返回的对象。
foo.call(thisObject)和foo.apply(thisObject)
在这种模式下,call和apply的第一个参数就是foo函数体内的this,
如果thisObject是null或undefined,那么会变成Global对象。
再来一串
这是sofish的例子
function findout(){ alert(this.str); } var obj = {}; obj.str = 'hi i\'m from the object u referred'; obj.fn = findout; obj.fn(); //object u referred function findout(){ alert(this.str); } window.str = 'hi global'; findout(); // hi global