説明させてください。私はその本を読んでいませんでしたが、ダグラス・クロックフォードのJavaScriptのClassical Inheritanceの記事には、Function.prototype.methodに関するその例に関連する重要な文が1つあります。
これを返します。値を返す必要のないメソッドを作成する場合、通常はこれを返すようにします。カスケードスタイルのプログラミングが可能です。
実際、私はその用語に精通していません。よく知られている用語は「FluentInterface」または「MethodChaining」だと思います。そのwikiページを読んでください。さまざまな言語の例があるので、理解できます。
PS。@Gianluca Bargelliは、Function.prototype.methodをこのように使用する例を提供するのが少し速かったので、回答には投稿しません。
アドオン:例の観点からどのように使用できるか:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
Number.method('integer', function () { // you add 'integer' method
return Math[this < 0 ? 'ceil' : 'floor'](this);
})
.method('square', function () { // you add 'square' method with help of chaining
return this * this;
});
console.info( (-10/3).integer().square() ); // <- again chaining in action
ご覧のとおり、integer()はNumberオブジェクトを返すため、次のように記述する代わりに、別のメソッドを呼び出すことができます。
var a = (-10/3).integer();
console.info( a.square() );
そして、それを使用する私の方法についてのいくつかの言葉、ほとんどの場合、私は「各メソッド-インデント付きの新しい行、私にとってこの方法はより読みやすい」と書くことを好みます。
Function.method('add', add)
.method('sub', sub)
.method('mul', mul)
.method('div', div);
このようにして、どこから始めたかがわかり、「改行/インデント」は、そのオブジェクトをまだ変更していることを示します。長い行と比較してください:
Function.method('add', add).method('sub', sub).method('mul', mul).method('div', div);
または典型的なアプローチ:
Function.method('add', add);
Function.method('sub', sub);
Function.method('mul', mul);
Function.method('div', div);
ADDON2:通常、Javaコードなどのエンティティを操作するときは、このアプローチ(Fluentインターフェイスパターン)を使用します。
public class Person {
private String name;
private int age;
..
public String getName() {
return this.name;
}
public Person setName( String newName ) {
this.name = newName;
return this;
}
public int getAge() {
return this.age;
}
public Person setAge( int newAge ) {
this.age = newAge;
return this;
}
..
}
Person
それは私が簡単な方法でオブジェクトを構築することを可能にします:
Person person = new Person().setName("Leo").setAge(20);
一部の人々はそれを少し異なって、彼らはset
/get
に新しい種類のメソッドを追加し、それを呼び出しますwith
:
public class Person {
private String name;
private int age;
..
public String getName() {
return this.name;
}
public void setName( String newName ) {
this.name = newName;
}
public Person withName( String newName ) {
this.setName( newName ); // or this.name = newName; up to you
return this;
}
public int getAge() {
return this.age;
}
public void setAge( int newAge ) {
this.age = newAge;
}
public Person withAge( int newAge ) {
this.setAge( newAge ); // or this.age = newAge; up to you
return this;
}
..
}
これで、前の例は次のようになります。
Person person = new Person().withName("Leo").withAge(20);
このように、setメソッドの意味を変更しません(つまり、拡張しないので、ほとんどの開発者が期待するように機能します...少なくとも人々はそのset
メソッドが何かを返すことを期待していません;))。これらの特別な方法の興味深い点の1つは、自己文書化を失う可能性がありますが、使用すると読みやすさが向上します(たとえば、Person
作成の場合のように、withName
私たちが何をしているのかを正確に伝えることができます。
続きを読む:
FluentInterface-マーティンファウラーによるそのパターンの説明
PHPでのFluent Interfaces
The Weekly Source Code 14-Fluent Interface Edition-私は短くて、長所と短所(および他のリソースへのリンク)を見るのに十分です