在自学JavaScript的过程中。开始扩展到OOP设计,并且不想继续,直到我知道我做的是正确的。
这是在JavaScript中格式化对象以及它的构造函数和方法的一种常见或公认的方法吗?我见过很多不同的方法(至少看起来是这样)。任何其他可能引起我注意的违规行为也会很好。
function Person(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
Person.prototype = {
fullName:function(){
return this.firstName + " " + this.lastName;
},
changeFirstName:function(name){
this.firstName = name;
},
changeLastName:function(name){
this.lastName = name;
},
changeAge:function(age){
this.age = age;
},
displayInfo:function(){
document.write("Fullname: " + this.fullName() + "<br />");
document.write("Age: " + this.age + "<br />");
}
}
// Was just testing the functions.
var person = new Person("first", "last", 20);
document.write(person.fullName() + "<br />");
person.changeFirstName("FIRST");
document.write(person.fullName() + "<br />");
person.displayInfo();发布于 2016-07-30 22:21:17
有几种用JavaScript编写类的技术,每种技术都有其优点和缺点。您使用的原型技术很好,但您应该注意以下几点:
)
正如Joseph说的,当您分配Person.prototype = {时,您正在覆盖原始原型,这可能会导致一些属性的丢失。如果您依赖于类的constructor属性,那么一旦覆盖了原型,就无法访问它。要保留constructor属性,可以将其添加到自定义原型中:
Person.prototype = {
constructor: Person,
fullName: function () {
return this.firstName + " " + this.lastName;
},
//...
}有关这个主题的更多信息,这两个堆栈溢出问题将深入到更多的细节:覆盖原型不良实践,使用原型最佳实践。
当您使用this.firstName = firstName时,您可以让person对象的用户完全访问该数据成员;他们可以使用person.firstName = "newName"直接修改它。对于Person类的所有数据成员来说,这都是正确的,这使得您的changeX函数过时。
如果您希望Person类中的数据是私有的,那么还有另一种利用闭包创建类的技术:
function createPerson(firstName, lastName, age) {
return {
getFirstName: function () {
return firstName;
},
getLastName: function () {
return lastName;
},
getAge: function () {
return age;
},
};
}这种技术的一个缺点是为类的每个实例创建单独的函数,而不是每个实例共享原型中的函数。
函数displayInfo在您的函数类中感觉不合适。作为一般实践,让每个类/函数/模块执行一个特定的任务更加明确。您的person类似乎做了两件事:为一个人管理数据并将其数据显示给html文档。内聚力较低的代码的一个缺点是,它可能会创建可能不应该存在的依赖关系。例如,Person类依赖于document对象,它在node.js设置中是不可用的。您可以考虑将displayInfo分解到它自己的函数中:
function displayPersonInfo(person) {
document.write("Fullname: " + person.fullName() + "<br />");
document.write("Age: " + person.age + "<br />");
}发布于 2016-07-30 21:53:37
这是用JavaScript编写近乎经典的OOP的最初方法,而且一切似乎都是正确的。然而,当你这样做的时候,有一个怪癖你应该知道。
默认情况下,函数的prototype属性是一个具有名为constructor的属性的对象。默认情况下,这将指向函数。但是,如果将原型定义为Constructor.prototype = {},则需要使用新对象覆盖对象,实质上是丢弃包含constructor的旧对象。虽然在大多数情况下您将不使用该属性,但它通常是有用的。
另一种方法,不是为函数的prototype对象分配一个新的对象,而是向它添加属性。
Person.prototype.fullName = function(){...}
Person.prototype.changeFirstName = function(){...}下面是一段代码:
displayInfo:function(){
document.write("Fullname: " + person.fullName() + "<br />");
document.write("Age: " + this.age + "<br />");
}除非您知道自己在做什么,否则非常不鼓励使用document.write。当你给document.write打电话时,它隐式调用document.open它清除页面,删除上面的所有内容,然后再编写。。在元素或控制台函数上使用DOM操作(如innerHTML ),以避免在编写输出时删除页面。
https://codereview.stackexchange.com/questions/136418
复制相似问题