challenge compsite

by mejileben

JavaScript

let Cleja = {
    fields: [],
    construct: function(){
        this.constructFunc().call(this);
        return Object.freeze(this);
    },
    constructFunc: function(){},
    addField: function(prmObj){
        // prmObjからプロパティを順に取得して変数に入れたい
        // param名も利用者が指定できるようにしたい
//        for(let prm in prmObj){
//            this[Object.keys({prm})[0]] = prm;
//        }
        return Object.assign(this,prmObj);
    },
    addInit(func){
        this.constructFunc = func.bind(this);
        return this;
    },
    create: function(){
        return function(spec){
            this.construct(spec);
        }.bind(this);
    }
}

let animal = Cleja.addInit(function(spec){
                 console.log(this,spec);
                 this.name = spec.name;
                 this.kind = spec.kind;
             })
             .addField({
                 say: function(){
                     console.log(this);
                     return talker({name: this.name}).say;
                 },
                 greet: function(){
                     console.log("greet");
                     if ( this.kind === 'dog' ) {
                         this.say( 'bow!' );
                     } else if ( this.kind === 'person' ) {
                         this.say('hello!');
                     }
                 }
             })
             .create();

let talker = Cleja.addInit(function(spec){
                 console.log(this,";");
                 this.name = spec.name;
             })
             .addField({
                 say: function(sound){
                     console.log(name,"said:",sound);
                 }
             })
             .create();

let hachi = animal({ name: 'Hachi', kind: 'dog' });
let taro  = animal({ name: 'Taro', kind: 'person' });

hachi.greet();
// Hachi said: bow!
taro.greet();
// Taro said: hello!