我知道一点Java,喜欢整个类和面向对象的编程风格。我正在了解JavaScript,发现它没有像Java和C++那样的“经典”面向对象风格,甚至没有一个简单的构造函数。程序员有很多选择。我做了这个,你觉得怎么样?像这样编写构造函数可以吗?
//constructor of Human
function Human(name, age, size, married) {
this.n = name;
this.a = age;
this.s = size;
this.m = married
this.printInformation = function() {
return "Name: " + this.n + ", Age: " + this.a + ", Size: " + this.s + ", Married: " + this.m;
};
}
var human1 = new Human("Lenny Linux", 42, "142cm", false);
window.alert(human1.printInformation());
它正在运行,所以我认为应该是可以的。但有一个问题:我还有其他选择。例如,使用这些“对象字面量”或所谓的它们。我可以这样做:
var human1 = {
name: "Lenny Linux",
age: 42,
size: "142cm",
married: false,
printInformation: function() {
//...
}
}
这个更快是吗?在我写完之后,有一个“人类”的对象需要初始化,而另一个则不需要。但我更喜欢另一个。因为它更容易让我忽略我的代码。但第一个例子并不像典型的JavaScript那样,对吧?所以我必须忘记关于Java的一切,使用特殊的JavaScript样式?还是我可以保持我的Java代码风格?你认为呢?
PS:对于第一个例子,还有一个问题困扰着我。我无法强制程序员在初始化构造函数时只使用布尔值,如果他在“married”变量上。但我真的想强迫他这样做。年龄也是如此:只能是整数……有什么好的想法吗?
谢谢!
Human1
和Human2
像这样声明:function Human1(name) { this.name = name; }
function Human2(name) { return { name: name }; }
,那么new Human1("John Doe") instanceof Human1
将是true
,但new Human2("John Doe") instanceof Human2
将是false
。 - icktoofay