LoginSignup
1
0

More than 5 years have passed since last update.

プロパティへのアクセスで文字列をつくる

Posted at

やってみたいこと

const a = This.is.a.pen;
// a = "This is a pen"

Thisオブジェクトのisプロパティのaプロパティのpenプロパティにアクセスすると"This is a pen"という文字列になる的なことをやってみたかった

やりかた

Proxyでできる

const L = function(){
    const text = [];
    const handler = {
        get: function(target, name){
            if(name === "_$"){
                return function(postfix){
                    if(postfix){
                        return text.join(" ") + postfix;
                    }else{
                        return text.join(" ");
                    }
                }
            }else if(name === "_"){
                return function(token){
                    text.push(token);
                    return p;
                }
            }else if(name === "$"){
                return function(){
                    text.push("\n");
                    return p;
                }
            }else{
                text.push(name);
                return p;
            }
        }
    }
    const p = new Proxy({}, handler);
    return p
}
const t = L().I.have._(2).apples.$()
             .This.is.a.pen._$(".");

// t === "I have 2 apples
//        This is a pen."
  • _$()で文字列出力
  • $()で改行
  • _(args: any)で途中に何か文字列とか追加

にしてみた

何につかえるの?

...

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0