PDA

View Full Version : Resolved JS OOP method with parameter??



XManBG
11-16-2013, 09:53 PM
Hi guys,

there is a roughly Background object definition with 4 layers like:


function Background(){

this.layer1 = new Layer(1);
this.layer2 = new Layer(2);
this.layer3 = new Layer(3);
this.layer4 = new Layer(4);

}

function Layer(number){

this.number = number;
this.image = ''; // Image file name is empty for now, I'd like to fill it out appropriate later
... more misc stuff ...

}

Let's say I'd like to define an additional method to the object Background, which takes a layer and does something to it, i.e. add a picture to the layer.
I've tried with following definition without success; FF25 did it, but IE10 crashes every time?!



function Background(){

this.layer1 = new Layer(1);
this.layer2 = new Layer(2);
this.layer3 = new Layer(3);
this.layer4 = new Layer(4);

this.addimage = function(layer){
layer.image = 'picture' + layer.number + '.jpg';
}
}

...

// ... and now I'd like to use my method

var background = new Background();
background.addimage(background.layer1);

Is there an error?!

jscheuer1
11-17-2013, 03:37 AM
I have IE 11. But in its IE 10 mode I have no problem:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function Background(){

this.layer1 = new Layer(1);
this.layer2 = new Layer(2);
this.layer3 = new Layer(3);
this.layer4 = new Layer(4);
this.addimage = function(layer){
layer.image = 'picture' + layer.number + '.jpg';
};
}

function Layer(number){

this.number = number;
this.image = ''; // Image file name is empty for now, I'd like to fill it out appropriate later
//... more misc stuff ...

}
var background = new Background();
background.addimage(background.layer1);
</script>
</head>
<body>
<script type="text/javascript">
document.write(background.layer1.image);
</script>
</body>
</html>

I get:


picture1.jpg

The only problem that I can think of is that perhaps 'background' and/or 'Background' are reserved words in the scope. Like if you were doing this in quirks mode perhaps. I used a standards invoking DOCTYPE.

XManBG
11-17-2013, 02:30 PM
Thanks John,

I was unsure about using of object like parameter.
On your suggestion I've changed all names to something not very usual and the problem was still there.

A little bit later, I realized that it was something inside my '//... more misc stuff ...' where I had some calculations with the picture size.
The problem was, that the calculations were performed before the pictures were really loaded. Sometimes the loading was quicker, and it functioned, but sometimes not, and it crashed.
After upgrading all picture loads with image.onload events, everything went just fine.

Cheers