我想创建一个简单的对象,然后使用构造函数来填充该对象,就像使用OOP语言一样。为什么Javascript不让我创建基本对象
person = new Object();
问题:在Javascript中声明对象的最佳方法是什么,以便它基本上遵循与Java和C ++相同的方式?
我希望能够在代码中使用它们之前添加对象属性。
代码:
<!DOCTYPE html>
<html>
<body>
<script>
person=new Object(); <-- will work with out this code
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " -- " + myFather.age);
</script>
</body>
</html>
答案 0 :(得分:2)
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.body.innerHTML=myFather.firstname + " -- " + myFather.age;
有效,你不需要person=new Object()
,因为你无论如何都要在函数声明中定义人。在javascript中,函数也是对象构造函数。这就是为什么你可以在函数上调用new
。
http://jsfiddle.net/camus/bBj8f/
问题:声明对象的最佳方法是什么? Javascript使它基本上遵循与Java相同的转换 和C ++?
Javascript不必遵循Java或C ++“约定”,Javascript不像Java或C ++那样工作。
答案 1 :(得分:1)
答案 2 :(得分:1)
只需对您的代码进行一次小的剖析:
在这里,您要创建一个内部有对象的(全局变量)。
person=new Object();
接下来你要创建一个名为person
的新函数:注意这不是一个带有函数值的变量。
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
之后,您使用named函数作为对象person
的隐式构造函数。
解决方案是创建变量person,将函数作为值,或者仅创建命名函数。
前者看看这个:
var person = function(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
对于后者,只需删除person = new Object();
行。
答案 3 :(得分:0)
解决方案:
删除行person = new Object();
,然后您的代码按预期工作。
原因:
您在代码中收到错误的原因是因为javascript中的功能提升(请参阅http://designpepper.com/blog/drips/variable-and-function-hoisting)。因此,函数player
首先被定义。之后,用emtpy对象(行player
)覆盖函数person = new Object();
。
所以这就是为什么会出现这样的错误:Uncaught TypeError: object is not a function
查看其他评论:
console.log(person); // logs function person(firstname,lastname,age,eyecolor) ...
person=new Object(); // here you overwrite your function
function person(firstname,lastname,age,eyecolor) // at this point the function is already declared
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
console.log(person); // logs Object {}
myFather=new person("John","Doe",50,"blue"); // Uncaught TypeError: object is not a function
console.log(myFather.firstname + " -- " + myFather.age);