有人可以帮我解决为什么我的javascript中的对象没有被创建?

时间:2017-01-18 20:13:59

标签: javascript html

我似乎总是得到JS lint的错误告诉我它无法完成。我已经包含了下面的脚本。有人可以告诉我为什么它不起作用?我是javascript的新手,我想赶上速度,但我遇到了这个问题。

<!Doctype html> doctype html
<head><br>head<br>script type="text/javascript" 
<script type="text/javascript"><br>
function President (name, number)<br>{
President.name = Obama;<br>
President.number = 44;<br>
President.name2 = Bush;<br>
President.number2 = 43;<br>
}

Var Obama = new President {"Barack H. Obama", 44};<br>
Var Bush = new President {"George W Bush", 43};<br>
</script>
</head>

/body tag<body>
<script type="text/javascript">
document.write(President.name + "loves" President.name2 + " because he is cool and is the " <br>

President.number2 " of the US ");
</script>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

你有很多错误。请参阅js fiddle here

首先,您的javascript中不能包含<br>。这是html

另一件事是当你调用一个函数时,你需要使用()而不是{} - 例如new President("Barack H. Obama", 44);

President函数中,您应该使用this来引用函数中的变量。即this.name = name;

定义变量时,需要使用小写的var

您已为President定义了两个参数 - 名称和编号。

function President (name, number){...}

然后当你创建一个新的总统时,你传递的两个论点是"Barack H. Obama"44

new President("Barack H. Obama", 44);

&#13;
&#13;
function President(name, number) {
  this.name = name;
  this.number = number;
}

var Obama = new President("Barack H. Obama", 44);
var Bush = new President("George W Bush", 43);

alert(Obama.name + " loves " + Bush.name + " because he is cool and is the " + Obama.number + " of the US");
&#13;
&#13;
&#13;

答案 1 :(得分:0)

此代码段存在许多语法问题。为了得到你想要的东西你需要做的事情:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function President (name, number){
    President.name = name;
    President.number = number;
}

var Obama = new President("Barack H. Obama", 44);
var Bush = new President("George W Bush", 43);
</script>
</head>

<body>
<script type="text/javascript">
document.write(Obama.name + "loves" + Bush.name + " because he is cool and is the " + Obama.number " president of the US ");
</script>
</body>
</html>

我们不会在JavaScript中使用<br>和其他HTML标记之类的内容。

另外,我们使用()来调用函数:

var Obama = new President("Barack H. Obama", 44);
var Bush = new President("George W Bush", 43);

此外,我们需要使用原型上的键并使用我们传入的值:

function President (name, number){
    President.name = name;
    President.number = number;
}

答案 2 :(得分:0)

<br>标记可以在javascript中实现,如下所示:

var mybr = document.createElement('br');
someElement.appendChild(mybr);