我刚刚开始学习OOP。我仍在尝试了解一切。我正在尝试制作一个新函数,该函数基本上将允许我通过传递所述类的参数来创建新对象。
这是否有可能,如果是,我在做什么错呢?
如上所述,仍然在学习,所以任何建议都会受到赞赏。
class Person {
constructor(name) {
this.persName = name;
}
myName() {
return "My name is " + this.persName;
}
}
function getPers(_perName, fullName) {
_personName = new Person(fullName);
}
$(document).ready(function() {
getPers(John, "John Doe");
});
您可以遵循以下示例。请注意,没有太多的逻辑初始化。该示例只是向您展示OOP如何工作。当然,还有很多其他更好的方法可以解决这个问题,但是对于第一次尝试,它应该很好用。
class Person {
//declare the constructor with required name values and optional age value
constructor(firstName, lastName, age = 0) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
//declare a typically setter, e.g. for age
setAge(age) {
this.age = age;
}
//declare a getter for the person with age
getPerson() {
return this.firstName + ' ' + this.lastName + ' is ' + this.age + ' years old.';
}
}
//here you got with some function within you need to define a new person
function getCreatedPerson(firstName, lastName, age = 0) {
//define the person with required firstname and lastname
const person = new Person(firstName, lastName);
//use the setter to set age of person
person.setAge(age);
//return the person by using the person getter
return person.getPerson();
}
//here you can call the createdPerson function
$(document).ready(function() {
console.log(getCreatedPerson('John', 'Doe', 32));
});
希望它有助于理解它的工作原理。