Drkcore

22 02 2011 javascript Tweet

恋するプログラムをJavascriptで(3-4)

3-4は継承を扱う。

ProductName 恋するプログラム―Rubyでつくる人工無脳
秋山 智俊
毎日コミュニケーションズ / ?円 ( 2005-04 )


クラスっぽく書く必要もないだろうとobject関数を作って継承させるようにした。

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

function Responder(name) {
  this.name = name;
  this.response = function (input) {
    return "";
  };
}

function WhatResponder(name) {
    var that = object(new Responder(name));
    that.response = function (input) {
    return input + 'ってなに?';
    };
    return that;
}

function RandomResponder(name) {
    var that = object(new Responder(name));
    that.responses = ['今日は寒いね','チョコ食べたい','昨日10円拾った'];
    that.response = function (input) {  
        return this.responses[Math.floor(Math.random() * 3)];
    };
    return that;
}
function Unmo(name) {
  this.name = name;
  this.responder = RandomResponder('Random');
  this.dialogue = function (input) {
    return this.responder.response(input);
  };
  this.responder_name = function () {
    return this.responder.name;
  };
}

var u = new Unmo('proto');
var input = "あれ";

console.log(u.dialogue(input));

クラスっぽく書きたい場合にはJavascriptパターンが参考になる。モダンな書き方ももちろん載っている。

ProductName JavaScriptパターン ―優れたアプリケーションのための作法
Stoyan Stefanov
オライリージャパン / 2940円 ( 2011-02-16 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021