【问题标题】:in javaScript factory pattern i am not g undefined value在 javaScript 工厂模式中,我不是未定义的值
【发布时间】:2018-04-23 16:25:41
【问题描述】:

var peopleFactory = function(name, age, height) {
  var temp = {};
  this.name = name;
  this.age = age;
  this.height = height;
  temp.printPerson = function() {
    console.log(this.name + '' + this.age + '' + this.height);
    document.write(this.name + '' + this.age + '' + this.height);
  };
  return temp;
};
var person1 = peopleFactory('tanmay', 27, 5.11);
var person2 = peopleFactory('chinmay', 37, 5.12);
person1.printPerson();
person2.printPerson();

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow!请使用tour 并通读help center,尤其是How do I ask a good question? 做你的研究,search 以获取有关 SO 的相关主题,然后试一试。如果您在进行更多研究和搜索后卡住并且无法解开,请发布您的尝试minimal reproducible example,并具体说明您卡在哪里。人们会很乐意提供帮助。祝你好运!
  • this.name = name; 应该是 temp.name = name;... 而其他的也是。

标签: javascript design-patterns factory


【解决方案1】:

不确定,但给你。让它成为一个类。

class peopleFactory {
  constructor(name, age, height) {
    this.name = name;
    this.age = age;
    this.height = height;
  }
  printPerson() {
    return this.name + ' ' + this.age + ' ' + this.height;
  };
};
var person1 = new peopleFactory('tanmay', 27, 5.11);
console.log(person1.printPerson())

【讨论】:

    【解决方案2】:

    您不应该在您的工厂中使用this,因为它是对全局对象的引用(除非您想使用new 关键字调用您的工厂。但是,它不再是工厂了)。

    相反,您可以使用另一个本地对象来存储对象的私有数据。通过这样做,您的 printPerson() 函数将成为一个闭包,并且可以访问该本地对象内的数据,并且一旦它被调用就能够打印它。

    var peopleFactory = function(name, age, height) {
      var temp = {}, instance = {};
    
      temp.name = name;
      temp.age = age;
      temp.height = height;
      instance.printPerson = function() {
        console.log(temp.name + ' ' + temp.age + ' ' + temp.height);
        document.write('<br/>' + temp.name + ' ' + temp.age + ' ' + temp.height);
      };
      return instance;
    };
    var person1 = peopleFactory('tanmay', 27, 5.11);
    var person2 = peopleFactory('chinmay', 37, 5.12);
    person1.printPerson();
    person2.printPerson();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多