首页 新闻 赞助 找找看

JavaScript代码的小小疑问(46)

0
[已解决问题] 解决于 2015-11-12 11:28

“...用一个函数将创建子类的代码包装起来,这样就可以在构造函数和方法链中使用父类的参数,而不需要写死某个类名的名字来使用它的参数。...(即类工厂)”

 

//这句话怎么理解?可以用简单代码说明下吗?

Coca-code的主页 Coca-code | 初学一级 | 园豆:10
提问于:2015-08-25 14:13
< >
分享
最佳答案
0
class Person{
  constructor(name, type){
    this.name = name;
    this.type = type;
  }
  static createChild(type){
    return type === 'boy': new Boy(): new Girl();
  }
}

class Boy extends Person{
  constructor(name, 'boy'){
    super(name);
  }
}

class Girl extends Person{
  constructor(name, 'girl'){
    super(name);
  }
}

Person.createChild('boy');

用了ES6的特性,简单看看吧。这句话描述得比较奇怪,个人感觉。

奖励园豆:5
幻天芒 | 高人七级 |园豆:37175 | 2015-11-12 10:37

大神厉害,学习了~ :-0

Coca-code | 园豆:10 (初学一级) | 2015-11-12 11:28
其他回答(1)
0
/// <summary>
    /// 父母
    /// </summary>
    public class Parents
    {
        //1Boy 0Girl
        public Parents GetChild(int WhatDoWant) {
            if (WhatDoWant == 1)
            {
                return new Boy(WhatDoWant);
            }
            else
            {
                return new Girl(WhatDoWant);
            }
        }

        public string Name { get; set; }

        public int Sex { get; set; }
    }

    /// <summary>
    /// 男孩
    /// </summary>
    public class Boy : Parents
    {
        public Boy(int sex)
        {
            this.Sex = sex;
        }
    }

    /// <summary>
    /// 女孩
    /// </summary>
    public class Girl : Parents
    {
        public Girl(int sex)
        {
            this.Sex = sex;
        }
    }

我是这样理解的。不对勿喷。

Dayiba狼 | 园豆:33 (初学一级) | 2015-08-25 15:43

谢谢,是c#吧~

支持(0) 反对(0) Coca-code | 园豆:10 (初学一级) | 2015-09-29 17:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册