【问题标题】:How to modify method pattern to prototypal如何将方法模式修改为原型
【发布时间】: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


【解决方案1】:

显然我需要修改我的代码看起来像这样,我现在得到正确的输出,将设置为已回答。谢谢

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;    methods removed
// this.introduce=introduce;
};
Human.prototype.introduce = function(){
    return "Hello I am" + " " + this.name;
}
//  const human2 = new Human("Jane", 25);
//  human2.getName();
//  human2.getNameAndAge();

const human4 = new Human("lilly", 30); // human4.introduce(); // => “你好,我是莉莉”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2013-06-16
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多