我创建简单对象无法正常工作

My creation of a simple object is not working correctly?

本文关键字:常工作 工作 创建 简单 单对象      更新时间:2023-09-26

我想创建一个简单的对象,然后使用构造函数来填充该对象,就像在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>
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++那样工作。

你的行

person=new Object();

这里不需要。只需删除该行,您的代码应该可以工作:http://jsfiddle.net/s5UDq/

只是对代码的一小部分剖析:

在这里,您正在创建一个包含对象的(全局变量)。

person=new Object();

接下来的行是创建一个名为 person 的新函数:请注意,它不是将该函数作为值的变量。

function person(firstname,lastname,age,eyecolor){
  this.firstname=firstname;
  this.lastname=lastname;
  this.age=age;
  this.eyecolor=eyecolor;
}

之后,您将命名函数用作对象person的隐式构造函数。

解决方案是创建一个可变人员,将函数作为值,或者只创建命名函数。

对于前者,请看一下:

  var person = function(firstname,lastname,age,eyecolor){
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
  }

对于后者,只需删除person = new Object();行。

解决方案:
删除该行person = new Object();,然后代码按预期工作。

原因:
你在代码中出现错误的原因是 javascript 中的函数提升(参见 http://designpepper.com/blog/drips/variable-and-function-hoisting)。因此,函数player首先被定义。之后,用 emtpy 对象(带有 person = new Object(); 行)覆盖函数player

所以这就是为什么会出现这样的错误: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);