2016-05-26 64 views
0

從來沒有處理對象,但現在寫的自定義對象來測試使用JavaScript自定義對象變量及其函數內部

function GraphicsObject(text) { 
      var type = text; 
      var map = new Object(); 
      alert("test"); 
     } 

    GraphicsObject.prototype.setAttribute = function(key, val) { 
      alert(type); // ReferenceError: type is not defined 
      this.map[key] = val; ReferenceError: map is not defined 
    }; 

爲什麼那些錯誤,爲什麼劇本不喜歡這種語法?

編輯

這是我如何使用對象

var g1 = new GraphicsObject("text"); 
+0

蘇雷什,那麼應該把大量的感覺給你。 ..地圖是他存儲屬性的對象... –

+0

@MichaelRouse是的。這說得通。太多的用法:) –

回答

1

問題的發生是因爲GraphicsObject

var type 
var map 

是私有變量,不能從外部訪問,即使您擴展它。

這裏是2個解決方案:

function GraphicsObject(text) { 
 
    this.type = text; 
 
    this.map = {}; 
 
    alert("GraphicsObject"); 
 
} 
 

 
GraphicsObject.prototype.setAttribute = function(key, val) { 
 
    this.map[key] = val; 
 
    alert('Type is: '+this.type); 
 
    alert('You\'re setting: '+key+' attribute with value: '+val); 
 
}; 
 

 

 
var GO = new GraphicsObject('some text'); 
 
GO.setAttribute('a', 'b');

和另一種解決方案:

function GraphicsObject(text) { 
 
    var type = text; 
 
    var attributes = {}; 
 
    
 
    this.setAttribute = function(key, val) { 
 
    attributes[key] = val; 
 
    alert('Type is: '+type); 
 
    alert('You\'re setting: '+key+' attribute with value: '+val); 
 
    } 
 
    
 
    // because variables are private You've to write getter method to return them 
 
    this.getAttribute = function(key) { 
 
    return attributes[key]; 
 
    } 
 

 
    this.setType = function(value) { 
 
    type = value; 
 
    } 
 

 
    this.getType = function() { 
 
    return type; 
 
    }; 
 
} 
 

 

 
var GO = new GraphicsObject('some text'); 
 
GO.setAttribute('a', 'b');

+1

哦,夥計。謝幕。第二個解決方案是完美的。 –

+0

看起來像你來自Java。因爲Java開發人員非常喜歡設置私有變量,並使它們可以通過setter/getters訪問(: – num8er

+1

)你讓我發現這裏是紅色的,謝謝你的幫助。 –

2

function GraphicsObject(text) { 
 
      // type and map are private variables 
 
      // var type = text; 
 
      // var map = new Object(); 
 
      this.type = text; 
 
      this.map = {}; // suggested by 
 
      alert("test"); 
 
     } 
 

 
GraphicsObject.prototype.setAttribute = function(key, val) { 
 
      alert(this.type); 
 
      this.map[key] = val; 
 
    };

+0

仍然有同樣的錯誤'ReferenceError:映射未定義' –

+0

的澄清,使用'this.variable'語法內部的函數實際上將它設置爲一個屬性,而不僅僅是一個範圍變量。然後,在訪問函數對象本身的屬性時,該屬性變得可訪問,而不僅僅在函數內部。 – shamsup

+0

當你在它的時候,把'new Object()'改成'{}' – Wainage

相關問題