gpt4 book ai didi

javascript - 如何在 Javascript 中创建类?

转载 作者:太空狗 更新时间:2023-10-29 14:41:36 24 4
gpt4 key购买 nike

这是我到目前为止得到的,它根本不起作用:(我的播放器类中的所有变量都是空的,更新永远不会被调用。

我的意思是编程类,而不是 css 类。 IE。不是 (.movi​​ngdiv{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>

编辑:好吧,我想我在这里搞砸了。我第一次尝试上课时似乎搞砸了。重试后,我现在似乎可以使用 Meders 帖子中的“1 Using a function”。

真正的问题似乎是javascript在我的真实代码中到达这一行时不知道该怎么做:

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

我放的时候它也好像会窒息

box.style.background-color

所以我现在需要回答的问题是如何设置一个值来为名称中带有“-”的 javascript 变量设置样式。我会在一秒钟内发布测试

最佳答案

根据 this文章中,在 JavaScript 中定义类的方式有以下三种:

1 使用函数

例子:

 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 使用 JSON

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


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

3 使用函数的单例

 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());

关于javascript - 如何在 Javascript 中创建类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3034274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com