【发布时间】:2021-08-03 23:11:12
【问题描述】:
好的,那么如何将以下代码从“构造函数模式”修改为原型模式? " 修改 Human 以在其方法方面使用原型设计模式。"
const getName = function () {
return "name: " + this.name;
};
const getNameAndAge = function () {
return ("name: " + this.name + " " + "age: " + this.age);
};
const introduce = function () {
return (" Hello I am " + this.name)
};
const Human = function (name, age) {
this.name = name;
this.age = age;
this.getName=getName;
this.getNameAndAge=getNameAndAge;
this.introduce=introduce;
};
// test cases
//const human2 = new Human("Jane", 25);
// human2.getName();
// human2.getNameAndAge();
//--------------------------------------------- ---------------------- 我是一名学生,目前正在学习 JS -> 模式、面向对象和继承。
请随时提供任何建议,即使它与主要问题无关。 到目前为止我的代码:
const getName = function () {
return "name: " + this.name;
};
const getNameAndAge = function () {
return ("name: " + this.name + " " + "age: " + this.age);
};
const introduce = function () {
};
const Human = function () {
this.name = name;
this.age = age;
this.introduce=introduce;
};
Human.prototype.introduce = function() {
return ( "Hello I am " + this.name + " and I am " + this.age + "
years old" );
}
const human4 = new Human("lilly", 30);
human4.introduce(); // => "Hello I am lilly"
【问题讨论】:
-
有什么建议吗:D?
标签: javascript design-patterns prototype