2014-04-28 32 views
1

我寫了一個練習班,誰能告訴我爲什麼打印2而不是1?在javascript class中的設定值

function hnclass(){ 
    var h=1; 
    function print(){ 
     console.info(h); //here it print 1 
    } 
    return { 
     item:h, 
     printout:print 
    } 
} 

hc=new hnclass(); 
hc.item=2; 
hc.printout(); 
console.log(hc.item); //here it print 2 

hc.item=2;我改變的item值,所以在那之後,當我打電話的打印功能應該打印出來2。我在想這可能沒有一個setter函數設定值在這種類中?

回答

1

誰能告訴我,爲什麼它打印2,而不是1

由於設置變量或屬性的值從未改變另一個變量或屬性的值。下面是一個簡單的例子:

var a = 1; 
var b = a; 
a = 42; 

分配一個新的價值a不會改變的b值,即使b有同樣的價值a最初。
在你的情況下,將值賦給hc.item根本不會改變h的值。

我在想這種類沒有setter函數設定值嗎?

是的,如果你還訪問x.itemprint

function hnclass(){ 
    var h=1; 
    function print(){ 
     console.info(obj.item); 
    } 
    var obj = { 
     item:h, 
     printout:print 
    }; 
    return obj; 
} 

然而,這整個的設置並沒有真正有什麼用面向對象或類。也許Introduction to Object-Oriented JavaScript可以幫助你更好地理解問題。

0

在您的'類'聲明中,h是一個局部變量。如果你想創建一個屬性,你必須做一些事情,如:

function hnclass() { 
    this.item = 1; // Here item is a attribute of your class 
    this.printout = function print() { 
     console.info(this.item); // Use this.item instead of h 
    } 
} 
hn = new hnclass() ; 
hn.printout() ; 
hn.item = 4 ; 
hn.printout() ; 

這是一個非常簡單的例子,你可以用prototype有一個更有條理的代碼。

0

你沒有寫一個類,你寫了一個函數。明確地指出你的錯誤。

  1. 您沒有使用this將變量範圍限定爲類,而是它們是私有變量。
  2. 您添加了一個覆蓋類定義的return語句。如果添加

    console.info(hc instanceof hnclass);

你會看到你的變量hc不是你的類的實例。

這裏是更正後的代碼。

function hnclass() { 
    var self = this; 
    this.item = 1; 
    this.printout = function print() { 
     console.info(this.item); 
    } 
} 
var hc = new hnclass(); 
hc.printout(); // will display 1 
hc.item = 4; 

console.info(hc instanceof hnclass); // will display true 
hc.printout(); // will display 4 
console.log(hc.item); // will display 4 

我建議你多學習閉包,確定範圍,功能從類的區別,以及如何測試一個變量屬於同一個的instanceof類。