1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript: 擬似文字列

1
Last updated at Posted at 2026-03-27

関数のprototypeに文字列のようなものを放り込んでおくと、instance生成時にあたかも最初から文字列が格納されているかのように振る舞う。

let f=function(){};
f.prototype=new String("testset");
let a=new f;
console.log(a[0]);
for(let b in a)console.log(b,a[b])

ただしこの方法ではStringのmethodは使えない(参照は可能)。

console.log(a.length,a.charAt,a.big,a.split);
a.charAt(0);a.big();a.split("")//error

ついでに言うとfor ofで巡回する事も出来ない(当然spread構文も使えない)。

error
for(let b of a)console.log(b)
a=[...a]

prototype.toStringを書き換えるとmethodを使えようになり、for ofで巡回も可能。

f.prototype.toString=function(){
	for(var a=0,b=this.length,c="";a<b;)c+=this[a++];
	return c
};
console.log(a.charAt(0),a.split(""),a.replace(/t/g,""))
for(let b of a)console.log(b)

prototype.valueOfも同様の関数にすれば利便性が増す。

用途

ではこんなものが何の役に立つのか? 残念ながらここにそれを書くには余白が狭過ぎる。勿論筆者がそんな事知るわけが無いなんて口が裂けても言えない

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?