私がこのコードを持っているとしましょう:
(function(global) {
function Bar(foo) {
this.foo = foo;
return this;
}
Bar.prototype.getFoo = function() {
return this.foo;
};
Bar.prototype.setFoo = function(val) {
return (this.foo = val);
};
})(this);
setFoo
withのような関数を作成することと、次のように実行することの違いは何ですかprototype
。
function Bar(foo) {
this.getFoo = function() {
return this.foo;
};
}
プロトタイプとは何か、そしてそれが何を意味するのかはわかっていますが、なぜ一部の人がプロトタイプで関数を割り当てるのか理解できません。これを割り当てると、Barの新しいインスタンスを作成するたびにそれらが利用できるようになるからです。