在动画CC帆布项目,我有几个MC的与这些连锁名库:card1
,card2
,card3
...,想使用JavaScript / HTML5代码,把一个随机MC在舞台上。
var container, c, card; // basic stuff
function init() {
c = createjs;
container = new c.Container();
stage.addChild(container);
var m = 1; // a random number
card = new lib.this["card" + m](); // GIVES ERROR. This is AS3 style.
//card = new lib.card1(); // WORKS FINE!
container.addChild(card);
card.x = 800;
card.y = 250;
}
我收到错误消息:
未捕获的TypeError:无法读取未定义的属性'card1'。
有什么想法吗?:)
card = new lib.this["card" + m](); // GIVES ERROR. This is AS3 style. // card = new lib.card1(); // WORKS FINE!
由此,我有两点要清除:
这是因为我们不使用this
关键字作为某些对象的属性。我们在对象的方法中使用它作为对其的引用。
var foo = { x: 1, y: 2 };
console.log(foo.this); // → undefined
console.log(foo.this["x"]); // → Type Error
var bar = { x: 1, y: 2, showX: function () { return this["x"] } }
console.log(bar.showX()); // → 1
但是您可以拥有一个名为的属性this
:
var foo { this: 1, that: 2 }
console.log(foo.this); // → 1
您可以使用一种.
或多种[]
符号(不需要this
)来访问对象的属性,如下所示:
var foo = { x: 1, y: 2 };
console.log(foo.x); // → 1
console.log(foo["y"]); // → 2
因此,您需要做的是:
card = new lib["card" + m]();
以下是使用div的示例。我尝试遵循您的代码以使其保持相似。所述lib
对象具有4个构造card1
以card4
作为属性,各发电卡与特定的颜色。
const createjs = {
Container: function () {
this.elt = document.createElement("div");
this.elt.classList.add("container");
}
},
Card = function () {
this.elt = document.createElement("span");
this.elt.classList.add("card");
},
lib = {
card1: function () {
this.elt = new Card().elt;
this.elt.style.background = "lightblue";
},
card2: function () {
this.elt = new Card().elt;
this.elt.style.background = "gold";
},
card3: function () {
this.elt = new Card().elt;
this.elt.style.background = "lightgreen";
},
card4: function () {
this.elt = new Card().elt;
this.elt.style.background = "#f76";
}
};
function init() {
let container = new createjs.Container().elt;
stage.appendChild(container);
for (let m = 1; m < 5; m++) {
let card = new lib["card" + m]().elt;
card.style.width = 80 + "px";
card.style.height = 100 + "px";
container.appendChild(card);
}
}
init();
#stage {
background: #e85;
height: 500px;
padding: 1px;
}
.container {
margin: 60px;
background: #fff3;
}
.card {
display: inline-block;
border-radius: 10px;
width: 80px;
height: 100px;
margin: 1em;
}
<div id="stage"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句