Javascript 在对象中存储对库对象的引用

Javascript 在对象中存储对库对象的引用,javascript,arrays,object,easeljs,Javascript,Arrays,Object,Easeljs,我有一个从easelJS库创建的对象,我想将它存储在一个对象中。我不确定是存储它还是访问它不正确,但当我稍后检查它时,该对象是未定义的 我的对象的一个例子是: var ShapeObject = function() { var self = this; var name; var shape; var rotation; var color; this.initialize = function(n, s) {

我有一个从easelJS库创建的对象,我想将它存储在一个对象中。我不确定是存储它还是访问它不正确,但当我稍后检查它时,该对象是未定义的

我的对象的一个例子是:

var ShapeObject = function() {
    var self          = this;

    var name;
    var shape;
    var rotation;
    var color;

    this.initialize = function(n, s) {
        name = n;
        shape = s;
        rotation = this.randomRange()+1; 
        color = this.randomColor();
    };    
};
我正在尝试创建和存储以下内容:

shapes = new Array();
for (i=0;i<2;i++) {
    var theShape = new createjs.Shape();

    sObject = new ShapeObject();
    sObject.initialize("shape"+i, theShape);
    shapes.push(sObject);
}
for (i=0;i<2;i++) {
    stage.addChild(shapes[i].shape);
}
shapes=newarray();

对于(i=0;i代码中的
shapeObject
没有
.shape
属性,因此
shapes[i]。shape
将是
未定义的

构造函数中声明的局部变量对于外部世界来说是不可见的属性。它们根本不是属性,只是局部变量。它们在
.initialize()
方法和构造函数的范围内,但不适用于任何其他对象

对象的公共属性必须通过设置
this.shape=xxx
在方法中初始化,其中
this
指向您的对象

您可以将
initialize()
方法更改为:

this.initialize = function(n, s) {
    this.name = n;
    this.shape = s;
    this.rotation = this.randomRange()+1; 
    this.color = this.randomColor();
}; 

然后,删除所有与这些属性同名的
var
声明。

代码中的
shapeObject
没有
。shape
属性,因此
shapes[i]。shape
将是
未定义的

构造函数中声明的局部变量对于外部世界来说是不可见的属性。它们根本不是属性,只是局部变量。它们在
.initialize()
方法和构造函数的范围内,但不适用于任何其他对象

对象的公共属性必须通过设置
this.shape=xxx
在方法中初始化,其中
this
指向您的对象

您可以将
initialize()
方法更改为:

this.initialize = function(n, s) {
    this.name = n;
    this.shape = s;
    this.rotation = this.randomRange()+1; 
    this.color = this.randomColor();
}; 

然后,删除所有与这些属性同名的
var
声明。

shape
name
和其他是函数范围内的变量,它们不是创建对象的一部分。
shape
name
和其他是函数范围内的变量,它们不是创建对象的一部分对象。非常简单但非常有用。我刚刚开始探索Javascript,非常感谢你的回答。我将进一步研究这个概念。非常简单但非常有用。我刚刚开始探索Javascript,非常感谢你的回答。我将进一步研究这个概念。