/    Sign up×
Community /Pin to ProfileBookmark

Working with Classes

Hi,

I want to learn to write code in the best possible way. Till now I would make the graphics using HTML and/or PHP and then use javascript dom properties to interact with them.
But I want my code to be very good so I can feel confident I know javascript.
I am making a very simple game and I got stuck when using classes.
So far the game makes a one-colored chess board.
Using the dom I got:

function create(){
for (i=0; i<8; i++){
for (j=0; j<8; j++){
x=document.createElement(‘div’)
x.style.height=55+”px”
x.style.width=55+”px”
x.style.borderColor=”yellow”
x.style.borderStyle=”solid”
x.style.borderWidth=5 +”px”

x.style.backgroundColor=”black”
x.style.position=”absolute”
x.style.left=j*65+”px”
x.style.top=i*
65+”px”
document.body.appendChild(x)
}
}
}

where

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<head>
<script style=”text/javascript” src=”game.js”>

</script>
</head>
<body onload=”create()”>
</body>
</html>

Is this ok? Or could it be done more elegant, while not using classes?

Then I thought I could use classes, and I got:

unction create(i,j){
this.id=7*i+j
this.style.height=55+”px”
this.style.width=55+”px”
this.style.borderColor=”yellow”
this.style.borderStyle=”solid”
this.style.borderWidth=5 +”px”
this.style.backgroundColor=”black”
this.style.position=”absolute”
this.style.left=j*
65+”px”
this.style.top=i*65+”px”
}
for (i=0; i<8; i++){
for (j=0; j<8; j++){
obj=new create(i,j)
document.body.appendChild(obj)
}
}

But what do I do with this: x=document.createElement(‘div’) – this isn’t a property, what is it?

Also isn’t style a property and the rest of the properties are it’s children?
Can somebody please show me how do you write this as elegant classes?
Thank you

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @RoxyBoo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.6,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...