开发者

Declaring objects as parameters doesn't work?

I get a "node not found" (DOM Exception 8) error when I later try to append objects I create with this code:

object.addimgs = function(a){
        for (var i = 0; i < a.length; i++){
            a[i][0] = create("img", {position: "absolute"}, {src: a[i][1]});
        }
}

The array I'm plugging in for a is this:

[[this.logo, "img/coffee.png"], [this.door, "img/door.png"]]

So essentially I'm trying to use a for loop to declare objects because it would be more efficient than what I had working be开发者_StackOverflow社区fore:

this.logo = create("img", {position: "absolute"}, {src: "img/coffee.png"});
this.door = create("img", {position: "absolute"}, {src: "img/door.png"});

... etc

(create(a, b, c){ is a custom function, I know the code above works)

Any ideas why this wouldn't be working? Do the objects stop being objects when they're entered in as a parameter?


I see what you are trying, but assigning to a[i][0] will assign to the array slot, not what the array slot contains.

Further, when you create the array like this:

[[this.logo, "img/coffee.png"], [this.door, "img/door.png"]]

The array element [0][0] is not a reference to the this.logo member as it looks like you are expecting. The array element [0][0] will contain the value of this.logo at the time that you create the array, which will most likely be undefined.

Try something like this instead:

object.addimgs = function(a){
    for (var i = 0; i < a.length; i++){
        a[i][0][a[i][1]] = create("img", {position: "absolute"}, {src: a[i][2]});
    }
}

Then call it with this array:

[[this, "logo", "img/coffee.png"], [this, "door", "img/door.png"]]


Whenever you have an <object>.<property> in JavaScript, it can either be used to return or set the value. It cannot be used as a pointer. In this case:

var o = {}
function setToFoo( v ){ v = "foo" }
setToFoo( o.foo );
console.log( o.foo ); // undefined

If you want to assign something dynamically, then you should be using array syntax: <object>["name"] = #value and assigning that way:

var a = [["logo", "img/coffee.png"], ["door", "img/door.png"]]
for (var i = 0; i < a.length; i++){
     this[a[i][0]] = create("img", {position: "absolute"}, {src: a[i][1]});
}

If I were building something like your method, however, I would actually be using key=>value mappings in a dynamic object to make it more obvious:

object.addimgs = function(obj, src){
   for (var it in src ){
       obj[it] = create("img", {position: "absolute"}, {src: src[it]});
   }
}

var src = {logo: "img/coffee.png", door: "img/door.png"}
var obj = // whatever your "this" is
object.addimgs(src, obj);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜