【问题标题】:Using JavaScript custom object variable inside its function在其函数中使用 JavaScript 自定义对象变量
【发布时间】:2016-05-26 20:36:04
【问题描述】:

从未处理过对象,但现在编写自定义对象进行测试

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");

【问题讨论】:

  • Suresh,那么它对你来说应该很有意义......地图是他存储属性的对象......
  • @MichaelRouse 是的。这说得通。这个用法太多了:)

标签: javascript object prototype


【解决方案1】:

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; 
   };

【讨论】:

  • 还是同样的错误ReferenceError: map is not defined
  • 为了澄清,在函数内部使用this.variable 语法实际上将它设置为一个属性,而不仅仅是一个作用域变量。然后在访问函数对象本身的属性时,该属性变得可访问,而不仅仅是在函数内部。
  • 当您使用它时,将new Object() 更改为{}
  • @Wainage 你也做了改变。没有运气。
  • @sᴜʀᴇsʜᴀᴛᴛᴀ 你是如何实例化对象的?
【解决方案2】:

出现问题是因为 GraphicsObject

var type
var map

是私有变量,不能从外部访问,即使你扩展它。

这里有两种解决方案:

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');

【讨论】:

  • 好像你来自Java。因为 Java 开发人员喜欢设置私有变量并使用 setter/getter 访问它们(:
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 2019-12-30
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多