今天在学习javascript的时候碰到了this,感觉它跟java里的有点不一样。然后上网查了一下,参考了这篇文章,JavaScript中this关键字详解,发现它们之间的区别主要是这样:
java:
1 public class TestThisInJava { 2 3 public static void main(String[] args) { 4 new B().showName();//a 5 } 6 } 7 class A { 8 String name = "a"; 9 public void showName() { 10 System.out.println(this.name); 11 } 12 } 13 class B { 14 String name = "b"; 15 public void showName() { 16 new A().showName(); 17 } 18 }
javascript:
1 var a= { 2 name: "a", 3 showName: function(){ 4 alert(this.name); 5 } 6 }; 7 8 var b = { 9 name: "b", 10 showName: a.showName 11 } 12 13 b.showName(); //a
可以看出在java中,this声明在哪里就this就指代声明处的对象,而在javascript中,this最上层是由谁调用的,this就指代谁。
原文:http://www.cnblogs.com/free-happy-coding/p/5133282.html