今天回顧了一下java基礎,突然發現自己把java和JavaScript中this的概念混淆了,所以記錄一下以備不時之需
java:
1.this它可以在類里面來引用這個類的屬性和方法
代碼:
public class Test { PRivate int x = 10; public Test(int x){ System.out.println("賦值前的全局變量"+this.x); System.out.println("形參x="+x); this.x = x; System.out.println("賦值后的全局變量"+this.x); } public static void main(String[] args) { Test t = new Test(11); }}
結果:
賦值前的全局變量10形參x=11賦值后的全局變量11
2.通過this 這個關鍵字返回自身這個對象
代碼:
public class ThisDemo { private int count ; //全局變量Java虛擬機都會先自動給它初始化為默認值。 而局部變量不行 public ThisDemo add(){ count++; return this; } public void print(){ System.out.println("count="+count); } public static void main(String[] args) { new ThisDemo().add().add().print(); }}結果:count=2
其中初始化賦值如下
Boolean false Char '/u0000'(null) byte (byte)0 short (short)0 int 0 long 0L float 0.0f double 0.0d
3.構造函數之間的調用
代碼:
public class ThisDemo { String name ; int age ; public ThisDemo(){ this.age = 21; } public ThisDemo(String name,int age){ this();函數有所屬對象時:指向所屬對象函數有所屬對象時:指向所屬對象 this.name = name; } public void print(){ System.out.println("賦值后的名字"+this.name); System.out.println("賦值后的年齡"+this.age); } public static void main(String[] args) { new ThisDemo("桂綸鎂",23).print(); }}
結果:
賦值后的名字桂綸鎂賦值后的年齡21
javascrip:
1.函數有所屬對象時:指向所屬對象
代碼:
var myObject = { value : 10 }; myObject.fun = function(){ var value = 100; alert(value); alert(this.value); alert(this); }; myObject.fun();
結果:100
10
Object
2.函數沒有所屬對象:指向全局對象(將上述代碼進行小小的改動)
代碼:
var myObject = { value : 10 }; myObject.fun = function(){ fun1 = function(){ alert("fun1:"+this.value); } var value = 100; alert(value); alert(this.value); alert(this); }; myObject.fun(); fun1();
結果:
100
10
Object
fun1:undefined
分析:
因為fun1()這個函數沒有綁定在任何一個對象上,所以它屬于window這個對象,所以它的this指的是全局變量,而全局變量沒有這個value
所以就為undefined
3.構造器中的 this:指向新對象
代碼:
var value = 10 ;fun = function(){ var value = 100; alert(this.value); alert(value);}fun();var f = new fun();
結果:
10
100
undefined
100
分析:我用了兩次調用來區分new一個函數和普通函數的區別,很明顯,當我new一個函數的時候,這時他所屬的對象是f,而f沒有value這個值,所以它的this.value為undefined
既然都是作用域,就擴展一下說一下apply()和call()的異同
相同點:兩個方法產生的作用是完全一樣的。
不同點:方法傳遞的參數不同
function A(){ this.flag = 'A'; this.tip = function(){ alert(this.flag); };};function B(){ this.flag = 'B';};var a = new A();var b = new B();a.tip.call(b);
a.tip.apply(b);
兩次運行結果都是B,注意這里tip是屬性所帶的方法,之前寫錯了看很久才發現,apply()和call()都是function.prototype里自帶的
總結一下:
java中this.value可以再本類中調用全局變量,也可以在構造器中用this()調用其他構造器,也可以用this表示當前對象
Javascript中this指的是這個函數所屬的對象的值,當new一個函數時,這個this就會指向這個new出來的對象,apply()和call()可以改變一個函數中this指向的對象
新聞熱點
疑難解答