最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How do I create a class in Javascript? - Stack Overflow

programmeradmin3浏览0评论

This is what I got so far, and it's not working at all :( all the variables are null in my player class and update never gets called.

I mean a programming class, not a css class. I.E. not (.movingdiv{color: #ff0000;})

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Class Test</title>
        <meta charset="utf-8" />
        <style>
            body { text-align: center; background-color: #ffffff;}
            #box { position: absolute; left: 610px; top: 80px; height: 50px; width: 50px; background-color: #ff0000; color: #000000;}
        </style>

        <script type="text/javascript">
            document.onkeydown=function(event){keyDown(event)};
            document.onkeyup=function(event){keyUp(event)};
            var box = 0;

            function Player () {
                var speed = 5;
                var x = 50;
                var y = 50;
            }

            function update() {
                box.style.left = this.x + "px";
                box.style.top = this.y + "px";
                box.innerHTML = "<h6 style=\"margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px;\">X: "+ this.x + "<br /> Y: " + this.y + "</h6>";
            }

            var player = new Player();
            var keys = new Array(256);
            var i = 0;
            for (i = 0;i <= 256; i++){
                keys[i] = false;
            }

            function keyDown(event){
               keys[event.keyCode] = true;
            }

            function keyUp(event){
               keys[event.keyCode] = false; 
            }

            function update(){
                if(keys[37]) player.x -= player.speed;
                if(keys[39]) player.x += player.speed;

                player.update();
            }

            setInterval(update, 1000/60);
        </script>
    </head>

    <body>
        <div id="box" ></div> 
        <script type="text/javascript">
            box = document.getElementById('box');
            box.innerHTML = "<h6 style=\"margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px;\">X: "+ player.x + "<br /> Y: " + player.y + "</h6>";
        </script>

    </body>
</html>

Edit: alright, I think I messed up here. The first time I tried to make a class I seem to have messed up. After retrying I seem to be able to now using the "1 Using a function" in Meders post.

the real problem seems to be that javascript doesn't know what to do when it gets to this line in my real code:

box.style.background-position = "" + -(this.frame * this.width) + "px " + -(this.state * this.height) + "px";

It also seems to choke anytime I put

box.style.background-color

So the question I need answered now is how do I set a value to style variables in javascript that have a "-" in the name. I'll post a test in a second

This is what I got so far, and it's not working at all :( all the variables are null in my player class and update never gets called.

I mean a programming class, not a css class. I.E. not (.movingdiv{color: #ff0000;})

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Class Test</title>
        <meta charset="utf-8" />
        <style>
            body { text-align: center; background-color: #ffffff;}
            #box { position: absolute; left: 610px; top: 80px; height: 50px; width: 50px; background-color: #ff0000; color: #000000;}
        </style>

        <script type="text/javascript">
            document.onkeydown=function(event){keyDown(event)};
            document.onkeyup=function(event){keyUp(event)};
            var box = 0;

            function Player () {
                var speed = 5;
                var x = 50;
                var y = 50;
            }

            function update() {
                box.style.left = this.x + "px";
                box.style.top = this.y + "px";
                box.innerHTML = "<h6 style=\"margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px;\">X: "+ this.x + "<br /> Y: " + this.y + "</h6>";
            }

            var player = new Player();
            var keys = new Array(256);
            var i = 0;
            for (i = 0;i <= 256; i++){
                keys[i] = false;
            }

            function keyDown(event){
               keys[event.keyCode] = true;
            }

            function keyUp(event){
               keys[event.keyCode] = false; 
            }

            function update(){
                if(keys[37]) player.x -= player.speed;
                if(keys[39]) player.x += player.speed;

                player.update();
            }

            setInterval(update, 1000/60);
        </script>
    </head>

    <body>
        <div id="box" ></div> 
        <script type="text/javascript">
            box = document.getElementById('box');
            box.innerHTML = "<h6 style=\"margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px;\">X: "+ player.x + "<br /> Y: " + player.y + "</h6>";
        </script>

    </body>
</html>

Edit: alright, I think I messed up here. The first time I tried to make a class I seem to have messed up. After retrying I seem to be able to now using the "1 Using a function" in Meders post.

the real problem seems to be that javascript doesn't know what to do when it gets to this line in my real code:

box.style.background-position = "" + -(this.frame * this.width) + "px " + -(this.state * this.height) + "px";

It also seems to choke anytime I put

box.style.background-color

So the question I need answered now is how do I set a value to style variables in javascript that have a "-" in the name. I'll post a test in a second

Share Improve this question edited Jun 13, 2010 at 23:45 William asked Jun 13, 2010 at 23:18 WilliamWilliam 8,80824 gold badges81 silver badges111 bronze badges 6
  • 1 What doesn't work? What is it supposed to do? – Marcel Korpel Commented Jun 13, 2010 at 23:21
  • all the variables are null in my player class and update never gets called. – William Commented Jun 13, 2010 at 23:26
  • Which update? I see two functions named update. And you're calling player.update, which doesn't exist. – Marcel Korpel Commented Jun 13, 2010 at 23:34
  • If you have an entirely new question, please make a new question and leave this question as is. – meder omuraliev Commented Jun 13, 2010 at 23:47
  • 1 Regarding the CSS property background-color: you should camelCase them, like box.style.backgroundColor. – Marcel Korpel Commented Jun 13, 2010 at 23:49
 |  Show 1 more comment

3 Answers 3

Reset to default 13

According to this article, there are three ways to define a class in JavaScript:

1 Using a function

Example:

 function Apple (type) {
     this.type = type;
     this.color = "red";
     this.getInfo = getAppleInfo;
 }

 function getAppleInfo() {
     return this.color + ' ' + this.type + ' apple';
 }


 var apple = new Apple('macintosh');
 apple.color = "reddish";
 alert(apple.getInfo());

2 Using JSON

 var apple = {
     type: "macintosh",
     color: "red",
     getInfo: function () {
         return this.color + ' ' + this.type + ' apple';
     }
 }


 apple.color = "reddish";
 alert(apple.getInfo());

3 Singleton using a function

 var apple = new function() {
     this.type = "macintosh";
     this.color = "red";
     this.getInfo = function () {
         return this.color + ' ' + this.type + ' apple';
     };
 }


 apple.color = "reddish";
 alert(apple.getInfo());

The var makes a private variable, do prefix with this instead in your constructor:

        function Player () {
            this.speed = 5;
            this.x = 50;
            this.y = 50;
            var pri = 'private';
            this.update = function() {
                  if(keys[37]) this.x -= this.speed;
                  if(keys[39]) this.x += this.speed;
            }
        }

        var player = new Player;
        alert( player.speed ) // should alert 5
        alert( player.pri ) // should fail or say undefined

You can also do...

      var player = {
           speed: 5,
           x:50,
           y:50,
           update: function() {
               // code
           }
      }

And then get rid of new Player and the Player constructor.

You're using Player like a constructor, but it is not set up like one.

Rather than using var inside the constructor function, like var speed = 5; you need to use

this.speed=5;

Then it wil return an instance of Player. As it is, you're just setting some variables and returning nothing in particular.

Now, as far as learning JS object creation and inheritance, I suggest checking out Douglas Crockford's resources. As you may know, it's not intended to be class-based like Java, PHP, Python and so on. JavaScript has prototypal inheritance based on cloning objects that already exist.

Crockford discusses doing class-based inheritance in JS in this older article. The problem is, you're not using JS to it's best trying to do that. This treatise may be interesting where he explains one way of cloning objects. That is the Object.beget method, which is good, but has limits as well. The best way is the 'functional' method. Sorry for the PowerPoint links, but you should read this: http://www.crockford.com/codecamp/The%20Good%20Parts%20ppt/4%20prototypal.ppt and this: http://www.crockford.com/codecamp/The%20Good%20Parts%20ppt/5%20functional.ppt

http://video.yahoo.com/watch/630959/2974197 is one version of a video where Crockford discusses the ins and outs of JS. http://www.youtube.com/watch?v=hQVTIJBZook is another of the same.

I really recommend getting the book JavaScript: The Good Parts for a thorough run down of pragmatic advanced JavaScript.

发布评论

评论列表(0)

  1. 暂无评论