在对象中存储对库对象的引用
Store reference to library object in object
我有一个从 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);
}
是否可以做我正在尝试的事情?
您代码中的 shapeObject
没有 .shape
属性,因此 shapes[i].shape
将是 undefined
。
在构造函数中声明的局部变量是对外界不可见的属性。它们根本不是属性,只是局部变量。它们在 .initialize()
方法和您的构造函数的范围内,但不在任何其他范围内。
Public 对象的属性必须在方法中通过设置 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
声明。
我有一个从 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);
}
是否可以做我正在尝试的事情?
您代码中的 shapeObject
没有 .shape
属性,因此 shapes[i].shape
将是 undefined
。
在构造函数中声明的局部变量是对外界不可见的属性。它们根本不是属性,只是局部变量。它们在 .initialize()
方法和您的构造函数的范围内,但不在任何其他范围内。
Public 对象的属性必须在方法中通过设置 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
声明。